Clear Filters
Clear Filters

Can anyone explain to me what is happening in this 'for' loop?

1 view (last 30 days)
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!

Accepted Answer

Roger Stafford
Roger Stafford on 28 Oct 2017
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.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!