For loop with the loop variable equal to a matrix

4 次查看(过去 30 天)
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 个评论
Rick
Rick 2014-8-7
Thanks, but why does it output k like this? I mean, it just does a column wise loop for no apparent reason.
Azzi Abdelmalek
Azzi Abdelmalek 2014-8-7
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
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by