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

Help vectorize this matrix multiplication

1,744 views
Skip to first unread message

Jim Rockford

unread,
Jun 24, 2011, 11:59:44 PM6/24/11
to
I have a matrix M for which I want to multiply each row by a scalar,
which can be different for each row.

One way to do it is as follows. Suppose the set of scalars are put
into a vector v. Then

diag(v) * M

effects this multiplication.

In my case, the problem is that constructing the diagonal matrix
diag(v) will exceed my computer memory. Obviously I could resort to a
loop, but I'm wondering if there is a different way to vectorize this
multiplication.

Thanks,
Jim

Nasser M. Abbasi

unread,
Jun 25, 2011, 12:19:38 AM6/25/11
to

What is wrong with just using bsxfun for this? (I do not understand
why you have to make a new matrix for).

EDU>> A=[1 2 3;4 5 6;7 8 9]

1 2 3
4 5 6
7 8 9

EDU>> v=[1 2 3]'
1
2
3


EDU>> bsxfun(@times,v,A)

1 2 3
8 10 12
21 24 27


--Nasser

Matt J

unread,
Jun 25, 2011, 3:26:04 AM6/25/11
to
"Nasser M. Abbasi" <n...@12000.org> wrote in message <iu3nkr$o40$1...@speranza.aioe.org>...

>
>
> What is wrong with just using bsxfun for this? (I do not understand
> why you have to make a new matrix for).
====================

Or, you could use a sparse diagonal matrix instead of a full one

N=length(v);
spdiags(v(:),0,N,N)*M;

Jim Rockford

unread,
Jun 25, 2011, 3:20:08 AM6/25/11
to
On Jun 25, 12:19 am, "Nasser M. Abbasi" <n...@12000.org> wrote:
> What is wrong with just using bsxfun for this? (I do not understand
> why you have to make a new matrix for).

Thanks. There's nothing wrong with using bsxfun to do this. I was
unaware of that function, which is why I was posting. It works great.

Jim

0 new messages