Can anyone explain to me what is happening in this 'for' loop?
1 次查看(过去 30 天)
显示 更早的评论
here is my code:
A=[1 2 3;11 12 13];
for i=A
A(i(1))=A(i(1))*4;
disp(i)
disp (A)
end
The matrix 'i' is equal to [1;11], then [2;12] and then [3;13]. Why? And why is my final matrix [4 8 3; 44 12 13]? Why are the numbers at (1,1) (1,2) and (1,2) the ones that changed?
Thanks!
0 个评论
采纳的回答
Roger Stafford
2017-10-28
The “for i=A” line is the source of oddity for your code. It should ordinarily be a row vector - that is, having only one row. As it stands it is sequentially equal to each successive column in A: [1;11], [2;12], [3;13] as you have seen. In the line
A(i(1))=A(i(1))*4;
i(1) is therefore successively 1, 2, then 3, so just the three elements of A: A(1), A(2), and A(3) are multiplied by 4. These are located at (1,1), (2,1), (1,2) in the natural linear order within the matrix A.
I have no idea what you intended for this code but it doesn’t look very useful as it is. If you wanted to multiply each element by 4, just "A = 4*A" would do that.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!