Matlab multiplies each row in the matrix by a different number

Say I have a matrix:

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

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

I can do this with loops, however, if for the purpose, where do they want us to use matrices. In the actual assignment A random number is populated, but each row that is multiplied sequentially.

Thanks, any help is much appreciated

+5
source share
2 answers

You just need to multiply the diagonal matrix by A like this.

 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 
+6
source

You can use bsxfun to accomplish this easily and quickly.

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

In newer versions of MATLAB (R2016b and later) you can really replace bsxfun just *

 out = [1 2 3 4].' * A; 
+5
source

Source: https://habr.com/ru/post/1258440/


All Articles