Ajax
Ajax

Reputation: 27

Multiply Matrix element in i-th row by the i-th element in the first row

I have the following matrix:

s=[1,2,3; 4,5,6;7,8,9];  

1| 2| 3  
4| 5| 6  
7| 8| 9  

Now I want each integer in the first row and i-th column to be multiplied by the corresponding i row number.

Desired output:

1 | 2  | 3  
8 | 10 | 12  
21| 24 | 27  

Upvotes: 2

Views: 103

Answers (3)

rahnema1
rahnema1

Reputation: 15837

Using bsxfun you can write:

bsxfun(@times,s,(1:size(s,1)).')

that in MATLAB R2016b or Octave ,thanks to implicit expansion, can be written as:

s .* (1:size(s,1)).'

Upvotes: 3

Tony Tannous
Tony Tannous

Reputation: 14876

s = [1,2,3; 4,5,6;7,8,9];

 1     2     3
 4     5     6
 7     8     9

[~, y] = size(s);
a = s(ones(y,1),:).';
b = a.*s;

b  = 
  1     2     3
  8    10    12
 21    24    27   

Upvotes: 2

aksadv
aksadv

Reputation: 806

Note that if A is diagonal matrix, then A*x scales the rows of x by the weights specified by the diagonal in A. So, for your problem you could simply use:

s = [1,2,3; 4,5,6;7,8,9];
%  1     2     3
%  4     5     6
%  7     8     9

s = diag([1:size(s,1)]) * s;
%  1     2     3
%  8    10    12
% 21    24    27

Upvotes: 5

Related Questions