フィルターのクリア

Elemental matrix multiplication [NxN] and [1xn] into [NxNxn]

6 ビュー (過去 30 日間)
William
William 2014 年 3 月 31 日
コメント済み: William 2014 年 3 月 31 日
Hi,
I want to multiply every element in A[NxN] by every value in B[1xn] to get C[NxNxn]
Current code:
for i = 1:n
c(:,:,i) = b(i) * a(:,:)
end
Is it possible to do this without the for loop to make it run faster?
Many thanks,

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 3 月 31 日
編集済み: Azzi Abdelmalek 2014 年 3 月 31 日
a=rand(4,3)
b=rand(1,6)
[n,m]=size(a)
p=numel(b);
c=reshape(bsxfun(@times, repmat(a(:)',numel(b),1),b')',n,m,p)
  2 件のコメント
John D'Errico
John D'Errico 2014 年 3 月 31 日
編集済み: John D'Errico 2014 年 3 月 31 日
That seems overly difficult the way you did it. Cleaner is just to reshape B first, THEN use bsxfun. No need at all to use repmat!
C = bsxfun(@times,A,reshape(B,[1,1,numel(B)]));
The idea is that BSXFUN will implicitly replicate as necessary those dimensions that are singleton (i.e., have a 1 in them.)
William
William 2014 年 3 月 31 日
That's great, faster now. Many thanks

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by