数组中最小的N个元素及其位置

时间:2017-01-11 13:25:49

标签: matlab

我有一个名为Acc_Std的数组,大小为1行,222列。

我需要在每个数组中使用最小的100值,但需要具有原始位置。

我已编写此代码,但实际上不起作用:

for Col = 1:222 

    [Std_Cont, Std_Loc]  = min(Acc_Std(:));
    Sort_Std_Cont(Col,1) = Std_Cont;
    Sort_Std_Loc(Col,1)  = Std_Loc;

    Acc_Std(Std_Loc) = []; % Here is the problem in my code
end 

1 个答案:

答案 0 :(得分:5)

使用both outputs of sort

% Example data
Acc_Std = randi(10, 1,10);

% Extract the smallest N elements
N = 3;

% Sort, while saving the original indices
[B, indices] = sort(Acc_Std);

% Now extract the N smallest elements
smallest_N = B(1:N);

% Check that they are indeed located at the
% indices returned by sort()
isequal(smallest_N, Acc_Std(indices(1:N)))

执行这个小脚本的结果:

ans =
     1