From: Chan Huntington on
I expect to be embarrassed by the answer to this, but...

I need to multiply each row of a matrix by the same row in a vector. To do this with a loop is simple, but seemingly inelegant. Any better thoughts.

The loop code would like like:
x = magic(3);
y = [1,2,3];
for i = 1:3
t = x(i,:)*y(i)
end

Thanks!
From: José David on
On 22 nov, 20:06, Chan Huntington <chann...(a)umich.edu> wrote:
> I expect to be embarrassed by the answer to this, but...
>
> I need to multiply each row of a matrix by the same row in a vector.  To do this with a loop is simple, but seemingly inelegant.  Any better thoughts.
>
> The loop code would like like:
> x = magic(3);
> y = [1,2,3];
> for i = 1:3
> t = x(i,:)*y(i)
> end
>
> Thanks!

Hi,

Maybe you can use something like this

n=3;
x = magic(n);
y = [1,2,3];
k=kron(y,x.');
t=(k(:,[1,n+2,2*n+3])).';

The last line just selects the rows that you want.

Greetings.
From: Doug Schwarz on
In article
<737102407.20922.1258916818172.JavaMail.root(a)gallium.mathforum.org>,
Chan Huntington <channing(a)umich.edu> wrote:

> I expect to be embarrassed by the answer to this, but...
>
> I need to multiply each row of a matrix by the same row in a vector. To do
> this with a loop is simple, but seemingly inelegant. Any better thoughts.
>
> The loop code would like like:
> x = magic(3);
> y = [1,2,3];
> for i = 1:3
> t = x(i,:)*y(i)
> end
>
> Thanks!

Check out bsxfun.

--
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.
From: Jan Simon on
Dear Chan!

> I need to multiply each row of a matrix by the same row in a vector. To do this with a loop is simple, but seemingly inelegant. Any better thoughts.
>
> x = magic(3);
> y = [1,2,3];
> for i = 1:3
> t = x(i,:)*y(i)
> end

At first I assume, that the rsulting t should be a matrix:
x = magic(3);
y = [1,2,3];
for i = 1:3
t(i, :) = x(i,:)*y(i)
end

Method 1: ONES
t = x .* y(ones(1, 3), :)'

Method 2: BSXFUN:
t = bsxfun(@times, x, y')

Kind regards, Jan
From: Chan Huntington on
I always know matlab has clever ways to do these things, just need to find them.... bsxfun it is, thanks all!