Elemental matrix multiplication [NxN] and [1xn] into [NxNxn]
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
William
am 31 Mär. 2014
Kommentiert: William
am 31 Mär. 2014
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,
0 Kommentare
Akzeptierte Antwort
Azzi Abdelmalek
am 31 Mär. 2014
Bearbeitet: Azzi Abdelmalek
am 31 Mär. 2014
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 Kommentare
John D'Errico
am 31 Mär. 2014
Bearbeitet: John D'Errico
am 31 Mär. 2014
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.)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!