For loop with the loop variable equal to a matrix

Hello, this block of code was given on a previous exam
M = [1 3 -2; 7 -5 1];
temp = 0;
for k = M
temp = temp + k(2)
end
temp
And we are supposed to give the final output of temp. I have no idea how one loops over a matrix, not even elements or anything. What the heck does k = M mean?
So I just do temp = 0+7 on the first iteration, but what happens on the next iteration? temp = 7 + 7?? I ran this code and got 3. Does the value of k(2) change or something?

답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2014년 8월 7일
Check what your code is doing
M = [1 3 -2; 7 -5 1]
temp = 0;
for k = M
'k=',k % Look at the value of k
temp = temp + k(2)
end
temp

댓글 수: 2

Thanks, but why does it output k like this? I mean, it just does a column wise loop for no apparent reason.
Each nth iteration, k takes the nth column
firdt iteration k=[1;7]
second iteration k=[3;-5]
and so on
Inside the loop, the second value k(2) is used

댓글을 달려면 로그인하십시오.

Joseph Cheng
Joseph Cheng 2014년 8월 7일

0 개 추천

So i would suggest save this as a .m file so you can use the break points. If you put a breakpoint at the for loop and you step through you can see that k iterates through the columns of the matrix M. In a normal for loop you'll have for k=1:10 which means k will loop through each iteration of 1 through 10. Similarly if you go for k=1:10:100 you'll get a k for each entry of 1:10:100.
With the break point you'll see that temp = temp +k(2). if we get rid of the (2) and just do temp = temp+k. you can see that in each iteration you'll be adding 1+3+-2 and 7+-5+1 with the result of [2;3]. So limiting the k(2) you'll only be adding using the second row.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2014년 8월 7일

답변:

2014년 8월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by