f

#### Multiply the ith column of a matrix by element at position i of a vector

```Hi, I would like to do something like:

for i=1:cols(M)
M(:,i) = M(:,i)*v(i)
end

Is there a fast/vectorized way to do this? Is this faster:

M = M*repmat(v,rows(M),1);

Thank you
Misha
```
 0
mk144210 (63)
5/10/2009 3:08:02 PM
comp.soft-sys.matlab 211266 articles. 19 followers. lunamoonmoon (257) is leader.

5 Replies
591 Views

Similar Articles

[PageSpeed] 4

```On May 10, 11:08=A0am, "Misha Koshelev" <mk144...@bcm.edu> wrote:
> Hi, I would like to do something like:
>
> for i=3D1:cols(M)
> =A0 =A0 =A0M(:,i) =3D M(:,i)*v(i)
> end
>
> Is there a fast/vectorized way to do this? Is this faster:
>
> M =3D M*repmat(v,rows(M),1);

That does not work.

If

A =3D R*M* C

where R and C are diagonal, then

a(i,j) =3D r(i)*m(i,j)*c(j)

i.e., r(i) multiplies each element in the ith row and c(j)
multiplies each element in the jth column. So, if r and c
are vectors,

A =3D diag(r)*M*diag(c)

Hope this helps.

Greg
```
 0
heath (3983)
5/10/2009 3:26:35 PM
```% Data
M = magic(5)
v = [6 7 8 9 10]

% Engine
D1 = bsxfun(@times,M,v);

% Compare to other method
for i=1:size(M,2)
D2(:,i) = M(:,i)*v(i);
end

all(D1(:)==D2(:))
```
 0
spamanon (2437)
5/10/2009 3:30:03 PM
```"Misha Koshelev" <mk144210@bcm.edu> wrote in message <gu6qkh\$3ut\$1@fred.mathworks.com>...
> Hi, I would like to do something like:
>
> for i=1:cols(M)
>      M(:,i) = M(:,i)*v(i)
> end
>
> Is there a fast/vectorized way to do this? Is this faster:
>
> M = M*repmat(v,rows(M),1);
>
> Thank you
> Misha

In general, use BSXFUN; if M is square (NxN) you can also use

M * diag(v)

hth
Jos
```
 0
10584 (930)
5/11/2009 6:02:01 AM
```"Jos " <#10584@fileexchange.com> wrote in message <gu8f0p\$ci1\$1@fred.mathworks.com>...

> if M is square (NxN) you can also use
>
> M * diag(v)
>

This works even for M is (M x N) rectangle, the only requirement is v has N elements.

Bruno
```
 0
b.luong5955 (6401)
5/11/2009 6:21:17 AM
```"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <gu8g4t\$pg0\$1@fred.mathworks.com>...
> "Jos " <#10584@fileexchange.com> wrote in message <gu8f0p\$ci1\$1@fred.mathworks.com>...
>
> > if M is square (NxN) you can also use
> >
> > M * diag(v)
> >
>
> This works even for M is (M x N) rectangle, the only requirement is v has N elements.
>
> Bruno

Yep! Thanks for correcting me, Bruno.
```
 0
10584 (930)
5/11/2009 6:41:01 AM