COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### multiply matrix with vector

• Email
• Follow

```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!!!
```
 0

See related articles to this posting

```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
```
 0

```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
```
 0

```Great! Thanks Jan!
"Jan Simon" <matlab.THIS_YEAR@nMINUSsimon.de> wrote in message <i22gpg\$qr1\$1@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
```
 0

```"Jan Simon" <matlab.THIS_YEAR@nMINUSsimon.de> wrote in message <i22gpg\$qr1\$1@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
```
 0