How to create a matrix with nested for loop for fraction entries?

2 ビュー (過去 30 日間)
Tanya Sharma
Tanya Sharma 2021 年 9 月 28 日
コメント済み: Mathieu NOE 2021 年 9 月 28 日
I want to create a matrix where x and g has values given as ii and jj.
The code runs fine but I want a 3 by 3 matrix as an output.
How to correct the code?
clear;
clc;
ii=0.5:.1:.7;
jj=.4:.1:.6;
mat=zeros(length(ii),length(jj));
mm=1;
for x=ii
kk=1;
for g=jj
y=1;
f=x*y*g;
mat(kk,mm)=f
kk=kk+1;
mm=mm+1;
end
end

採用された回答

Mathieu NOE
Mathieu NOE 2021 年 9 月 28 日
hello
here are a few mods to get a correct 3 x 3 output
clear;
clc;
ii=0.5:.1:.7;
jj=.4:.1:.6;
mat=zeros(length(ii),length(jj));
kk=1;
for x=ii
mm=1;
for g=jj
y=1;
f=x*y*g;
mat(kk,mm) = f ;
mm=mm+1;
end
kk=kk+1;
end
  2 件のコメント
Tanya Sharma
Tanya Sharma 2021 年 9 月 28 日
Thanks a lot Mathieu. Helped me perfectly.
Mathieu NOE
Mathieu NOE 2021 年 9 月 28 日
My pleasure
Have to admit @Rik 's suggestion is very valuable too.

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

その他の回答 (1 件)

Rik
Rik 2021 年 9 月 28 日
Why use loops at all?
y=1;
ii=0.5:.1:.7;
jj=.4:.1:.6;
[ii,jj]=ndgrid(ii,jj);
mat=ii.*y.*jj;
disp(mat)
0.2000 0.2500 0.3000 0.2400 0.3000 0.3600 0.2800 0.3500 0.4200
  1 件のコメント
Tanya Sharma
Tanya Sharma 2021 年 9 月 28 日
Great. This too works efficiently. Thanks a lot Rik.

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by