From: Jurriaan on
Hi I have a quite similar question as the topic "regarding matrix multiplication". However, this time, we will sum over the same dimension as used in the for loop.

Given vector A and matrix B, I would like to obtain D as follows.

A = [1:12];
B = rand(2,3,4,5,length(A))
for ii=1:length(A)
C(:,:,:,:,ii) = A(ii)*B(:,:,:,:,ii);
end
D = sum(C,5);

Is there a solution for avoiding the for loop?

Thanks for your help.
From: Steven Lord on

"Jurriaan " <j.bakker(a)erasmusmc.nl> wrote in message
news:hp584j$kkr$1(a)fred.mathworks.com...
> Hi I have a quite similar question as the topic "regarding matrix
> multiplication". However, this time, we will sum over the same dimension
> as used in the for loop.
>
> Given vector A and matrix B, I would like to obtain D as follows.
>
> A = [1:12];
> B = rand(2,3,4,5,length(A))
> for ii=1:length(A)
> C(:,:,:,:,ii) = A(ii)*B(:,:,:,:,ii); end
> D = sum(C,5);
>
> Is there a solution for avoiding the for loop?

RESHAPE A to be 1-by-1-by-1-by-1-by-numel(A) then use BSXFUN.

--
Steve Lord
slord(a)mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ


From: Matt J on
"Jurriaan " <j.bakker(a)erasmusmc.nl> wrote in message <hp584j$kkr$1(a)fred.mathworks.com>...
> Hi I have a quite similar question as the topic "regarding matrix multiplication". However, this time, we will sum over the same dimension as used in the for loop.
>
> Given vector A and matrix B, I would like to obtain D as follows.
>
> A = [1:12];
> B = rand(2,3,4,5,length(A))
> for ii=1:length(A)
> C(:,:,:,:,ii) = A(ii)*B(:,:,:,:,ii);
> end
> D = sum(C,5);
>
> Is there a solution for avoiding the for loop?
==============

The same solution as I initially posted in that other thread is applicable

s=size(B);
C=reshape( reshape(B,[],12)*A(:) ,s(1:end-1));