Reputation: 27
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
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
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
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