Use forLoop to manipulate values of elements in a specific column

12 ビュー (過去 30 日間)
JZ
JZ 2015 年 12 月 5 日
コメント済み: lsutiger1 2015 年 12 月 6 日
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

採用された回答

Star Strider
Star Strider 2015 年 12 月 5 日
This works:
mat = zeros(5:5);
mat(:,4) = 0:10:10*(size(mat,1)-1);
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
  4 件のコメント
JZ
JZ 2015 年 12 月 5 日
編集済み: JZ 2015 年 12 月 5 日
That is indeed a much simpler solution - thank you!
And thanks for the clarification on cell/element. No offense taken.
Star Strider
Star Strider 2015 年 12 月 5 日
My pleasure!

サインインしてコメントする。

その他の回答 (1 件)

lsutiger1
lsutiger1 2015 年 12 月 5 日
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 件のコメント
JZ
JZ 2015 年 12 月 5 日
Thanks, but I am still getting errors with both of your suggestions:
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
mat(i,4) = mat(i-4,4) + 10;
Index exceeds matrix dimensions.
mat(i) = mat(i-1,4) + 10;
Index exceeds matrix dimensions.
Suggestions?
lsutiger1
lsutiger1 2015 年 12 月 6 日
That's because you used i-4 rather than i-1.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by