multiply specific column of a matrix by specific element

조회 수: 17 (최근 30일)
Debanjan Maity
Debanjan Maity 2018년 12월 5일
편집: per isakson 2020년 9월 12일
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]

답변 (1개)

per isakson
per isakson 2018년 12월 5일
편집: per isakson 2018년 12월 5일
>> 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
Rajat Maheshwari
Rajat Maheshwari 2020년 9월 12일
편집: per isakson 2020년 9월 12일
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 2020년 9월 12일
편집: per isakson 2020년 9월 12일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by