Use forLoop to manipulate values of elements in a specific column
이전 댓글 표시
I created the following 5x5 matrix with no data:
mat = zeros(5:5)
mat =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
I would like to use a for loop to generate the following result
mat =
0 0 0 0 0
0 0 0 10 0
0 0 0 20 0
0 0 0 30 0
0 0 0 40 0
I attempted using the following code, but the operation was performed on the first column - not the 4th, as I had intended.
for i = 2:length(mat(:,4))
mat(i) = mat(i-1) + 10;
end
This was the actual result
mat =
0 0 0 0 0
10 0 0 0 0
20 0 0 0 0
30 0 0 0 0
40 0 0 0 0
I imagine this is a simple syntax problem, but I am not finding the solution in any of the forums. Any help is appreciated.
Thanks
채택된 답변
추가 답변 (1개)
lsutiger1
2015년 12월 5일
0 개 추천
You have only specified the row that you want to manipulate; you need to specify both the row and column.
mat(i) = mat(i-1,4) + 10;
댓글 수: 4
Walter Roberson
2015년 12월 5일
Perhaps you mean
mat(i,4) = mat(i-4,4) + 10;
?
lsutiger1
2015년 12월 5일
Yep. I left a comment on his question, rather than an answer, so as I was writing an actual answer I missed it.
Life of a coder.
JZ
2015년 12월 5일
lsutiger1
2015년 12월 6일
That's because you used i-4 rather than i-1.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!