Reputation: 115
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
Reputation: 30046
From the documentation:
M = min(A,[],dim)
returns the smallest elements along dimensiondim
. For example, ifA
is a matrix, thenmin(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 ofA
and returns them in output vectorI
.
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