Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

0 views
Skip to first unread message

Misha Koshelev

unread,
May 10, 2009, 11:08:02 AM5/10/09
to
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

Greg Heath

unread,
May 10, 2009, 11:26:35 AM5/10/09
to

That does not work.

If

A = R*M* C

where R and C are diagonal, then

a(i,j) = 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 = diag(r)*M*diag(c)

Hope this helps.

Greg

Matt Fig

unread,
May 10, 2009, 11:30:03 AM5/10/09
to
% 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(:))

Jos

unread,
May 11, 2009, 2:02:01 AM5/11/09
to
"Misha Koshelev" <mk14...@bcm.edu> wrote in message <gu6qkh$3ut$1...@fred.mathworks.com>...

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

M * diag(v)

hth
Jos

Bruno Luong

unread,
May 11, 2009, 2:21:17 AM5/11/09
to
"Jos " <#10...@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

Jos

unread,
May 11, 2009, 2:41:01 AM5/11/09
to
"Bruno Luong" <b.l...@fogale.findmycountry> wrote in message <gu8g4t$pg0$1...@fred.mathworks.com>...

Yep! Thanks for correcting me, Bruno.

0 new messages