Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Determining answers from a for loop?

4 vues (au cours des 30 derniers jours)
Marlee Shaffer
Marlee Shaffer le 15 Mar 2017
Clôturé : MATLAB Answer Bot le 20 Août 2021
I was given a practice midterm exam with sample questions, and the last one gave me a code and asked me to determine what the variable maximum would contain. The code was:
if true
% code
end
clear
A = [10 1 7;
4 3 6;
6 9 2];
[rows,cols] = size(A);
for c = 1:cols
maximum(c) = A(1,c);
for r = 1 : rows
if A(r,c) < maximum(c)
maximum(c) = A(r,c);
end
end
end
disp(maximum)
I plugged it into Matlab to get the variable maximum to be [4, 1, 2], however I do not get Matlab to use on my midterm so I have to know why it gives me those numbers. Could someone please explain why I got the numbers I did when I ran the code, and how I should go about tackling a loop question like this?? Thanks!

Réponses (1)

Roger Stafford
Roger Stafford le 15 Mar 2017
Whoever devised that problem has a fiendish sense of humor. It is actually calculating the minimum of each of the three columns in A. For example, for c = 1, indicating the first column of A, it starts “maximum(c)” with the first row element of that column. If the next column element is smaller, that smaller element replaces the “maximum(c)” value. When it finishes, it obviously has the minimum, not maximum, value for the column, which in this case is 4. This is something you can do in your head without using matlab.

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by