multiply specific column of a matrix by specific element

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)

>> 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

if i want to multiply the third column with another number say 3 alongwith the 2nd column multiplied by 2 and want to get result as
[1 4 9; 4 10 18; 7 16 27]
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
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 Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 5 Dec 2018

Edited:

on 12 Sep 2020

Community Treasure Hunt

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

Start Hunting!