Matlab multiply each row in matrix by different number
Asked Answered
D

2

7

Say that I have a matrix:

A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ; 10 11 12];

Is there a way to multiply :
row 1 by 1
row 2 by 2
row 3 by 3
and so on?

I am able to do this with for loops, however it if for an assignment where they want us to use matrices. In the actual assignment A is filled with random number but each row which by multiplied consecutively.

Thanks, any help is much appreciated

Daegal answered 19/10, 2016 at 1:24 Comment(1)
Have a look at the bsxfun function - it does exactly what you're looking to do.Gariepy
I
9

You just need to multiply a diagonal matrix by A like so.

A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ; 10 11 12];
disp(diag([1 2 3 4]) * A);

 1     2     3
 8    10    12
21    24    27
40    44    48
Isatin answered 19/10, 2016 at 1:38 Comment(0)
B
6

You can use bsxfun to accomplish this easily and very quickly

out = bsxfun(@times, [1 2 3 4].', A)

In newer versions of MATLAB (R2016b and newer) you can actually replace bsxfun with simply *

out = [1 2 3 4].' * A;
Belia answered 19/10, 2016 at 2:44 Comment(1)
gosh, that .' was what I was looking for over hours! Thanks.Hobson

© 2022 - 2024 — McMap. All rights reserved.