How to use if-then with matrix indices

1 回表示 (過去 30 日間)
Shan  Chu
Shan Chu 2016 年 5 月 3 日
回答済み: Guillaume 2016 年 5 月 3 日
Hi, I got a matrix n by n of a symbolic value a. And I want to change the value of a based on the matrix indices.
syms a
n=50;
z=ones(n)*a;
for i=1:1:n
for j=1:1:n
if j=1 or j=i then a=4
else a=8
Could you please help? thanks

採用された回答

Guillaume
Guillaume 2016 年 5 月 3 日
You certainly don't need a loop to generate your a.
a = ones(n) * 8; %default value everywhere
[rows, cols] = ndgrid(1:n); %matrices of row and column indices
a(rows == 1 | rows == cols) = 4; %substitute when condition is met
Note that because your i and j variables are meaningless, it's not clear whether you meant it to be column 1 or row 1 that get sets to 4. I assume it was rows but it's obvious how to change it to columns. Using variable names with meaning makes the code much clearer. Moreover i and j are actually functions in matlab, so are not recommended as variable names anyway.

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2016 年 5 月 3 日
編集済み: Andrei Bobrov 2016 年 5 月 3 日
n = 50;
z = ones(n)*8;
z(:,1) = 4;
z(eye(n)>0) = 4;
  2 件のコメント
Shan  Chu
Shan Chu 2016 年 5 月 3 日
sorry, actually a=4 when j=1 and j=i
Andrei Bobrov
Andrei Bobrov 2016 年 5 月 3 日
corrected

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


Torsten
Torsten 2016 年 5 月 3 日
n = 50;
z = ones(n)*8;
z(:,1)=4;
z(eye(n)==1)=4;
Best wishes
Torsten.

カテゴリ

Help Center および File ExchangeEquation Solving についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by