For loop with the loop variable equal to a matrix
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
0 commentaires
Réponses (2)
Azzi Abdelmalek
le 7 Août 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 commentaires
Azzi Abdelmalek
le 7 Août 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
Joseph Cheng
le 7 Août 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!