Using FOR IF loops to calculate MIN (NOT using MIN)
Show older comments
I have an array which is 36x41 and I need to find the minimum value and it's position. I've done this using the MIN function, but I need to check it with my own loop.
I know I need to set my A to equal something, and then be less than something but I can't figure out what. Any ideas where I'm going wrong?
A=
mincol=1;
minrow=1;
for x=1:31
for y=1:46
if A < [x y]
minrow=x
mincol=y
end
end
end
Answers (1)
Azzi Abdelmalek
on 18 Oct 2013
1 vote
What if A < [x y] means?
9 Comments
Katy
on 18 Oct 2013
Azzi Abdelmalek
on 18 Oct 2013
I think you should look at the getting started with Matlab
Katy
on 18 Oct 2013
Cedric
on 18 Oct 2013
Note that with <= you get the last entry which has the minimal value, whereas with only < you would get the first.
Katy
on 18 Oct 2013
Cedric
on 18 Oct 2013
No, but you could find them afterwards, with e.g.
[X,Y] = find( A == A(minrow,mincol) ) ;
Here X, and Y are vectors with all row and column IDs of elements of A which are equal to the minimum that your code just found.
Katy
on 18 Oct 2013
Cedric
on 18 Oct 2013
It's starting to be complicated if the FOR loop has to determine all mins. You have to stack locations and reset stacks when you find a lower element, e.g.
m = Inf ;
rows = [] ;
cols = [] ;
for rowId = 1 : size(A, 1)
for colId = 1 : size(A, 2)
if A(rowId,colId) < m
m = A(rowId,colId) ;
rows = rowId ;
cols = colId ;
elseif A(rowId,colId) == m
rows = [rows, ... you complete, see note.
cols = [cols, ... you complete, see note.
end
end
end
Note: I cannot give you the full answer, otherwise it's cheating. If you understand the concept, you'll be able to complete and test that it is working.
Braxton Reese
on 12 Oct 2015
seeing as it has been 2 years, would care to finish this up?
Categories
Find more on Loops and Conditional Statements 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!