Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Determining answers from a for loop?

조회 수: 4 (최근 30일)
Marlee Shaffer
Marlee Shaffer 2017년 3월 15일
마감: MATLAB Answer Bot 2021년 8월 20일
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!

답변 (1개)

Roger Stafford
Roger Stafford 2017년 3월 15일
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.

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by