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!