Storing values in a matrix out of nested for loops

1 回表示 (過去 30 日間)
SM
SM 2022 年 4 月 30 日
コメント済み: SM 2022 年 5 月 3 日
I am trying to write a code where I want to store the values out of element wise multiplication using three for loops. I tried a lot but it only shows values for a particular iteration. Each number in the matrices have to be multiplied with every other number of the other two matrices and the results to be stored in one row or column matrix. Kindly help.
m1=[0.5; 0.5];
m2=[0.6; 0.4];
m3=[0.2; 0.8];
m=[m1 m2 m3];
s1=m(:,1);
s2=m(:,2);
s3=m(:,3);
s5=zeros(1,8);
for i=1:length(s1)
for j=1:length(s2)
for k=1:length(s3)
s4=s1(i).*s2(j).*s3(k);
end
end
end

採用された回答

Akira Agata
Akira Agata 2022 年 4 月 30 日
how about the following?
m1 = [0.5; 0.5];
m2 = [0.6; 0.4];
m3 = [0.2; 0.8];
[q, p, r] = meshgrid(m2, m1, m3);
s4 = p.*q.*r;
disp(s4)
(:,:,1) = 0.0600 0.0400 0.0600 0.0400 (:,:,2) = 0.2400 0.1600 0.2400 0.1600
  3 件のコメント
Akira Agata
Akira Agata 2022 年 5 月 2 日
Please modify slightly, like below:
But I'm not sure why "0.8" appears twice in your s5 (3rd and 8th elements)
m1 = [0.5; 0.5];
m2 = [0.6; 0.4];
m3 = [0.2; 0.8];
[q,r, p] = meshgrid(m2, m3, m1);
s = p.*q.*r;
s = s(:);
disp(s)
0.0600 0.2400 0.0400 0.1600 0.0600 0.2400 0.0400 0.1600
SM
SM 2022 年 5 月 3 日
Thanks a lot! This works fine.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by