gpbdr13
gpbdr13

Reputation: 115

Index of Min of each line in a matrix without loop

I work on a matrix like this :

A=[1,2,3;5,4,6;9,8,7];

I want to get the index of each line. Here it is : Index = [1;2;3]

But how can I get this without a loop ?

I do this for the moment :

for k=1:length(A)
    [~,Index(k)] = min(A(k,:));
end

Upvotes: 1

Views: 72

Answers (1)

Wolfie
Wolfie

Reputation: 30046

From the documentation:

M = min(A,[],dim) returns the smallest elements along dimension dim. For example, if A is a matrix, then min(A,[],2) is a column vector containing the minimum value of each row.

Looking at output options, you can see

[M,I] = min(___) finds the indices of the minimum values of A and returns them in output vector I.

You were already using the second part of the above documentation notes, so just combine the two...

A=[1,2,3; 5,4,6; 9,8,7];
[~, idx] = min(A, [], 2);
% result: idx = [1; 2; 3];

Upvotes: 2

Related Questions