31 lines
880 B
Matlab
31 lines
880 B
Matlab
function [v, idx] = owuitools_topk (x, k, direction, fname, varargin)
|
|
%OWUITOOLS_TOPK Shared body of the maxk/mink shims.
|
|
|
|
if (~isempty (varargin))
|
|
error ('%s: this shim takes only (x, k) - no dimension or option arguments', fname);
|
|
end
|
|
if (~isnumeric (x) && ~islogical (x))
|
|
error ('%s: x must be numeric', fname);
|
|
end
|
|
if (~isnumeric (k) || ~isscalar (k) || k < 0 || k ~= fix (k))
|
|
error ('%s: k must be a non-negative integer', fname);
|
|
end
|
|
|
|
if (isvector (x) || isempty (x))
|
|
[sorted, order] = sort (x(:), direction);
|
|
n = min (k, numel (sorted));
|
|
v = sorted(1:n);
|
|
idx = order(1:n);
|
|
if (size (x, 1) == 1 && ~isempty (x)) % a row in, a row out
|
|
v = v.';
|
|
idx = idx.';
|
|
end
|
|
return;
|
|
end
|
|
|
|
[sorted, order] = sort (x, 1, direction);
|
|
n = min (k, size (sorted, 1));
|
|
v = sorted(1:n, :);
|
|
idx = order(1:n, :);
|
|
end
|