How can I use a nested for loop to find multiple minimum values in a matrix array?
Mostrar comentarios más antiguos
I am looking to write a script that will determine what the minimum value in a matrix is, and where it is located (it occurs more than once). I have written a code that will find a single minimum, but I'm struggling to adapt it for more than one minimum. This is a homework so any hints would be greatly appreciated. here is my code so far for matrix A.
A=[12,44,7,32,3;66,32,3,55,9;14,53,28,3,5];
MinVal=A(1,1);
RowVal=1;
ColVal=1;
for i=1:3
for j=1:3
if A(i,j)<MinVal;
MinVal=A(i,j);
RowVal=i;
ColVal=j;
end
end
end
formatspec='The minimum value is %0.2f in row %0.0f and column %0.0f.\n';
fprintf(formatspec,MinVal,RowVal,ColVal)
Respuesta aceptada
Más respuestas (2)
Simplify your code by using a linear index
ind = 1;
minval = A(ind);
for i =1:numel(A)
if A(i) < minval
minval = A(i);
ind = i;
elseif A(i) == minval
ind = [ind i]; % add current index
end
end
Convert linear index to sub scripts:
[i j] =ind2sub(size(A), ind)
It is easy to get the row and column indices of the minimum without any loops using code vectorization. This is faster and much more efficient than using nested loops:
>> A = [12,44,7,32,3;66,32,3,55,9;14,53,28,3,5];
>> X = min(A(:));
>> [R,C] = find(A==X)
R =
2
3
1
C =
3
4
5
One can also display the text without any loops:
>> fmt = 'The minimum value is %0.2f in row %0.0f and column %0.0f.\n';
>> fprintf(fmt,[X*ones(size(R)),R,C].')
The minimum value is 3.00 in row 2 and column 3.
The minimum value is 3.00 in row 3 and column 4.
The minimum value is 3.00 in row 1 and column 5.
3 comentarios
Thorsten
el 14 de Oct. de 2015
It's homework, so min is probably not allowed.
Guillaume
el 14 de Oct. de 2015
As it's homework I assume the OP has to use a loop. Otherwise, yes, a loop is pointless.
Stephen23
el 14 de Oct. de 2015
I realize this is probably homework and restricted to loops, but in case someone is browsing Answers or using an internet search engine then there needs to be atleast one answer that gives a more efficient solution to this problem, and links to the reasons why using loops is a poor solution.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!