Reputation: 99
I am multiplying two matrices by a vector using loop
. Is it possible to do that without using loop
?
Something like D1=C.*(A.*B)
is not working.
Below sample of code
clear;
clc;
A=rand(5,5);
B=rand(5,5);
C=[0.1 0.3];
for ii=1:2
D(:,:,ii)=A.*B.*C(ii);
end
Upvotes: 1
Views: 94
Reputation: 2462
You can do that with mostly matrix indexing:
clear;
clc;
A=rand(5,5);
B=rand(5,5);
C=[0.1 0.3];
% Get matrices to final size
A = A(:,:,ones(length(C),1)); % repeat into third dimension as many times as length(C)
B = B(:,:,ones(length(C),1)); % repeat into third dimension as many times as length(C)
C = C(ones(1,size(A,2)),:,ones(1,size(A,1))); % make it size size(A,2)xlength(C)xsize(A,1)
C = permute(C,[3 1 2]); % change to correct order
D = A.*B.*C;
Or as one liner (faster,requires less memory and doesn't change input variables):
D = A(:,:,ones(length(C),1)).*B(:,:,ones(length(C),1)).*permute(C(ones(1,size(A,2)),:,ones(1,size(A,1))),[3 1 2]);
Still, i think for most matrices sizes bsxfun
is faster (and better readable). But solving stuff with indexing is a lot more fun :P
Upvotes: 1
Reputation: 26069
this how to do it:
D=bsxfun(@times,A.*B,permute(C,[3 1 2]))
Explanation: the trick is to change C
from a row vector (say x-direction) to the 3rd dimension (or z-direction) using permute
, which is as if you would have defined C differently:
C(:,:,1)=0.1;
C(:,:,2)=0.3;
Now, bsxfun
is a compact way to do the for loop you wrote. that's it.
Upvotes: 3