Using FOR IF loops to calculate MIN (NOT using MIN)

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)

What if A < [x y] means?

9 Comments

If A is less than the value in position (x,y), where A is my array name
I figured it out thankyou.
mincol=1;
minrow=1;
for x=1:46
for y=1:31
if A(x,y) <= A(minrow,mincol)
minrow=x;
mincol=y;
end
end
end
A(minrow,mincol)
Note that with <= you get the last entry which has the minimal value, whereas with only < you would get the first.
Thankyou, I thought with <= I'd get all the minimum values, if there was more than one location with the minimum value
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.
Thankyou! I've used this for my next question, but with my FOR loop I need to make the loop find all the minimums in the data and then give all the locations in a seperate array....now I'm stuck again!
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.
seeing as it has been 2 years, would care to finish this up?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 18 Oct 2013

Commented:

on 12 Oct 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!