how can i create this matrix

10 ビュー (過去 30 日間)
shlomo shnur
shlomo shnur 2019 年 12 月 30 日
コメント済み: Matt J 2019 年 12 月 30 日
hello,
i'm new to this software and i couldn't find an explanation to this
I have a matrix that is defined like this:
A(ij) , 1<=j<=7 , 1<=i<=8
if i>j then 2j-1
if i<=j then 4j-2i
how can i write it in the software?
Thanks for your help

回答 (3 件)

Matt J
Matt J 2019 年 12 月 30 日
編集済み: Matt J 2019 年 12 月 30 日
A=nan(7,8);
[I,J]=ndgrid(1:7,1:8);
A(I>J)=2*J(I>J)-1;
...
  2 件のコメント
shlomo shnur
shlomo shnur 2019 年 12 月 30 日
it doesn't work for me .
i copied it to the command window and i got an error :
"Unable to perform assignment because the left and right sides have a different number of elements."
Matt J
Matt J 2019 年 12 月 30 日
Fixed.

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


Stephen23
Stephen23 2019 年 12 月 30 日
>> [I,J] = ndgrid(1:7,1:8);
>> X = I>J;
>> M = (2+2*~X).*J.*X - 2.*~X.*I - X
M =
-2 -2 -2 -2 -2 -2 -2 -2
1 -4 -4 -4 -4 -4 -4 -4
1 3 -6 -6 -6 -6 -6 -6
1 3 5 -8 -8 -8 -8 -8
1 3 5 7 -10 -10 -10 -10
1 3 5 7 9 -12 -12 -12
1 3 5 7 9 11 -14 -14

shlomo shnur
shlomo shnur 2019 年 12 月 30 日
found a solution:
I=8;
J=7;
A=ones(I,J);
for I=1:8
for J=1:7
if I>J
A(I,J)=(2*J-1);
elseif I<=J
A(I,J)=(4*J-2*I);
end
end
end
2 6 10 14 18 22 26
1 4 8 12 16 20 24
1 3 6 10 14 18 22
1 3 5 8 12 16 20
1 3 5 7 10 14 18
1 3 5 7 9 12 16
1 3 5 7 9 11 14
1 3 5 7 9 11 13
thank you for the help !
  1 件のコメント
Stephen23
Stephen23 2019 年 12 月 30 日
Your matrix dimensions are swapped: matrices are defined by rows and columns, so your original specification "A(ij) , 1<=j<=7 , 1<=i<=8" requires a 7x8 matrix, not an 8x7 matrix like in your answer.
In any case, using loops is not a particularly neat use of MATLAB.

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

カテゴリ

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