For loop with the loop variable equal to a matrix

3 views (last 30 days)
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?

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 7 Aug 2014
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 Comments
Rick
Rick on 7 Aug 2014
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 on 7 Aug 2014
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

Sign in to comment.


Joseph Cheng
Joseph Cheng on 7 Aug 2014
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!