Avoid for loop in multi-dimensional problem

1 回表示 (過去 30 日間)
Howard Wilton
Howard Wilton 2022 年 11 月 21 日
コメント済み: Howard Wilton 2022 年 11 月 21 日
I am looking to create a 3D matrix the achieves the following:
A(:,:,1)=[0 -2*pi; 2*pi 0]; A(:,:,2)=[0 -4*pi; 4*pi 0];
Ultimately, I am trying to solve , which in this instance will evaluate to 0. But for now, I just want to figure out how to build the matrix .
I have the following code:
l=0:1; q=0:1; p=2*pi*(1:2);
sub = l(:)-q(:).' % gives a 2x2 matrix
sub2 = repmat(sub,[1 1 2]) % repeats the 2x2 matrix to give a 2x2x2 matrix
for p_ = 1:length(p)
A(:,:,p_) = p(p_)*sub2(:,:,p_);
end
I am looking to conduct a multiplation that yields without having to use a for loop. Any suggestions would be appreciated.

採用された回答

Stephen23
Stephen23 2022 年 11 月 21 日
編集済み: Stephen23 2022 年 11 月 21 日
Some ideas:
format compact
A = cat(3,[0,-2*pi;2*pi,0],[0,-4*pi;4*pi,0]) % use CAT()
A =
A(:,:,1) = 0 -6.2832 6.2832 0 A(:,:,2) = 0 -12.5664 12.5664 0
A = pi*cat(3,[0,-2;2,0],[0,-4;-4,0]) % take out the commom PI
A =
A(:,:,1) = 0 -6.2832 6.2832 0 A(:,:,2) = 0 -12.5664 -12.5664 0
A = pi*cat(3,2,4).*[0,-1;1,0] % multiply two arrays
A =
A(:,:,1) = 0 -6.2832 6.2832 0 A(:,:,2) = 0 -12.5664 12.5664 0
A = cat(3,2,4).*[0,-pi;pi,0] % multiply two arrays
A =
A(:,:,1) = 0 -6.2832 6.2832 0 A(:,:,2) = 0 -12.5664 12.5664 0
  1 件のコメント
Howard Wilton
Howard Wilton 2022 年 11 月 21 日
thank you sir!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by