How could this be achieved in one line of code?
Show older comments
My professor suggested it's possible to do the following with a single line of code:
From some 2-D matrix "A", pull out the row numbers of the minimum value in each column, and store them in "OutVec". For example, given the matrix
A =
43 40 73 32 92 91
56 91 78 6 25 78
78 65 35 30 24 43
The expected output would be
outVec =
1
1
3
2
3
3
I am almost able to get there with
find(A == min(A, [], 1))
which returns
ans =
1
4
9
11
15
18
But of course these are linear indeces, and I'm looking only for row numbers. I thought about taking
rem(find(A == min(A, [], 1)), 3)
but then of course everything in the output that should be a 3 becomes a 0.
This is part of an assignment, but only as a challenge. It's not graded differently whether it's done in one line or multiple, and I could definitely do this in two or three lines. I'm just curious how it could be done in one. Thanks.
4 Comments
Joseph Reese
on 17 Apr 2018
David Fletcher
on 17 Apr 2018
Edited: David Fletcher
on 17 Apr 2018
Actually, the min function by itself will give you what you want - you don't need to use the find function -
A =[43 40 73 32 92 91;
56 91 78 6 25 78;
78 65 35 30 24 43]
[~,index]=min(A)
index =
1 1 3 2 3 3
Joseph Reese
on 17 Apr 2018
Edited: Joseph Reese
on 17 Apr 2018
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!