How can I use a nested for loop to find multiple minimum values in a matrix array?
Afficher commentaires plus anciens
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)
Réponse acceptée
Plus de réponses (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 commentaires
Thorsten
le 14 Oct 2015
It's homework, so min is probably not allowed.
Guillaume
le 14 Oct 2015
As it's homework I assume the OP has to use a loop. Otherwise, yes, a loop is pointless.
Stephen23
le 14 Oct 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.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!