For loop with the loop variable equal to a matrix

4 ビュー (過去 30 日間)
Rick
Rick 2014 年 8 月 7 日
回答済み: Joseph Cheng 2014 年 8 月 7 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by