multiply specific column of a matrix by specific element

138 views (last 30 days)
Say I have a matrix [1 2 3; 4 5 6; 7 8 9]. I want to multiply only the 2nd column by 2 & get the result as [1 4 3; 4 10 6; 7 16 9]

Answers (1)

per isakson
per isakson on 5 Dec 2018
Edited: per isakson on 5 Dec 2018
>> A = [1 2 3; 4 5 6; 7 8 9];
>> A(:,2) = A(:,2)*2
A =
1 4 3
4 10 6
7 16 9
>>
In response to comment
>> A .* [1,2,3]
ans =
1 4 9
4 10 18
7 16 27
  4 Comments
Rajat Maheshwari
Rajat Maheshwari on 12 Sep 2020
Edited: per isakson on 12 Sep 2020
A = [1 2 3 4; 5 6 7 8; 9 10 11 12];
c = A.*[rats(1./sum(A,1))]
I want to Write one line expression that will multiply each column of A by a scalar so that, in the resulting matrix, every column sums to 1. this [rats(1./sum(A,1))] is giving the reciprocal 1*4 vector but when I am multiplying with A.* it is giving error
per isakson
per isakson on 12 Sep 2020
Edited: per isakson on 12 Sep 2020
One-liners are more difficult to debug. And more difficult to read and understand.
You need to read the documentation on rats() again, especially: "S = rats(X) returns a character vector ". Why do you try to use rats() in the first place?
%%
C = A.*(1./sum(A,1));
sum(C,1)
outputs
ans =
1 1 1 1
>>
C = A./sum(A,1); is shorter and introduces less floating point errors

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!