multiply specific column of a matrix by specific element
Afficher commentaires plus anciens
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]
Réponses (1)
per isakson
le 5 Déc 2018
Modifié(e) : per isakson
le 5 Déc 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
>>
And see Array Indexing
In response to comment
>> A .* [1,2,3]
ans =
1 4 9
4 10 18
7 16 27
4 commentaires
Debanjan Maity
le 5 Déc 2018
per isakson
le 5 Déc 2018
See my answer.
Rajat Maheshwari
le 12 Sep 2020
Modifié(e) : per isakson
le 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
le 12 Sep 2020
Modifié(e) : per isakson
le 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
Catégories
En savoir plus sur Operators and Elementary Operations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!