Wisam
Wisam

Reputation: 27

Smallest N elements of an array with their location

I have an array called Acc_Std of size 1 Row and 222 Columns.

I need to have the smallest 100 values in each that array but with their original location.

I have written this code but, actually, doesn't work:

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 

Upvotes: 0

Views: 48

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

Use 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)))

Result of executing this little script:

ans =
     1

Upvotes: 5

Related Questions