From: stani S. on
Hi,

I have 3 dim matrix A(x,y,z) and a vector V(1,z). I want to multiply each slice of A(:,:,b) with the scalar V(b), b=1:z. What is the fastest way to do it?
Thanks!!!
From: Jan Simon on
Dear stani,

> I have 3 dim matrix A(x,y,z) and a vector V(1,z). I want to multiply each slice of A(:,:,b) with the scalar V(b), b=1:z. What is the fastest way to do it?

bsxfun(@times, A, V)

Jan
From: Jan Simon on
Dear stani,
>
> > I have 3 dim matrix A(x,y,z) and a vector V(1,z). I want to multiply each slice of A(:,:,b) with the scalar V(b), b=1:z. What is the fastest way to do it?
>
> bsxfun(@times, A, V);
*Wrong*. Then the 2nd dimension is multiplied. Better:
bsxfun(@times, A, reshape(V, 1, 1, numel(V)))
Now V is a [1 x 1 x z] array and the auto-expansion works as wanted.

Jan
From: stani S. on
Great! Thanks Jan!
"Jan Simon" <matlab.THIS_YEAR(a)nMINUSsimon.de> wrote in message <i22gpg$qr1$1(a)fred.mathworks.com>...
> Dear stani,
> >
> > > I have 3 dim matrix A(x,y,z) and a vector V(1,z). I want to multiply each slice of A(:,:,b) with the scalar V(b), b=1:z. What is the fastest way to do it?
> >
> > bsxfun(@times, A, V);
> *Wrong*. Then the 2nd dimension is multiplied. Better:
> bsxfun(@times, A, reshape(V, 1, 1, numel(V)))
> Now V is a [1 x 1 x z] array and the auto-expansion works as wanted.
>
> Jan
From: James Tursa on
"Jan Simon" <matlab.THIS_YEAR(a)nMINUSsimon.de> wrote in message <i22gpg$qr1$1(a)fred.mathworks.com>...
> Dear stani,
> >
> > > I have 3 dim matrix A(x,y,z) and a vector V(1,z). I want to multiply each slice of A(:,:,b) with the scalar V(b), b=1:z. What is the fastest way to do it?
> >
> bsxfun(@times, A, reshape(V, 1, 1, numel(V)))
> Now V is a [1 x 1 x z] array and the auto-expansion works as wanted.
>
> Jan

Another option:

mtimesx(A, reshape(V, 1, 1, numel(V)))

MTIMESX can be found here:

http://www.mathworks.com/matlabcentral/fileexchange/25977-mtimesx-fast-matrix-multiply-with-multi-dimensional-support


James Tursa