次元の違う配列の乗算について
Show older comments
M×N×Aの配列に対して、M×Nの配列を各Aの要素毎に乗算する方法を教えてください。
例えばX1=randi(100,[3,3,10])とC = [1 1 1; 2 2 2; 3 3 3];を用意してfor文を使った場合
n=size(X1,3);
for i=1:n
X2(:,:,i)=X1(:,:,i).*C;
end
とすれば一応計算できますが、配列のサイズが大きくなるとfor文計算が非常に時間がかかってしまいます。
for文を使わずに計算する方法はありますでしょうか。
宜しくお願いします。
Accepted Answer
More Answers (1)
Akira Agata
on 6 Jul 2023
Edited: Akira Agata
on 6 Jul 2023
配列 C を 3次元方向に繰り返して X1 とおなじサイズにすることで、ドット (.) による要素毎の乗算が可能です。
% サンプル配列
X1 = randi(100, [3, 3, 10]);
C = [1 1 1; 2 2 2; 3 3 3];
% C を3次元方向に繰り返して X1と同じサイズにする
n = size(X1, 3);
C2 = repmat(C, [1 1 n]);
% 要素毎の乗算
X2 = X1.*C2;
% サンプル配列
X1 = randi(100, [3, 3, 10]);
C = [1 1 1; 2 2 2; 3 3 3];
% ページ毎の乗算
X3 = pagemtimes(X1, C);
Categories
Find more on 線形代数 in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!