Multiplying each column of a matrix with a specific value

조회 수: 29 (최근 30일)
Areesh Adil
Areesh Adil 2020년 2월 4일
댓글: Areesh Adil 2020년 2월 4일
I have a matrix
mat=[2,1,0,0;1,0,0,0;0,0,0,1]
I want to multiply the first column by 25, the second column by 5, the third column by 10 and the fourth column by 1 in a way that I get:
mat=[50,5,0,0;25,0,0,0;0,0,0,1]
Also, can the answer be generalized as I might end up adding more rows later on.
Thanks

채택된 답변

James Tursa
James Tursa 2020년 2월 4일
편집: James Tursa 2020년 2월 4일
mat=[2,1,0,0;1,0,0,0;0,0,0,1]; % 2D matrix
f = [25,5,10,1]; % row vector
result = f .* mat; % element-wise multiply with virtual expansion of row vector
If you have an earlier version of MATLAB, then use bsxfun:
result = bsxfun(@times,f,mat); % same functionality as f .* mat
  댓글 수: 1
Areesh Adil
Areesh Adil 2020년 2월 4일
Thank you so much
I came up with a convoluted way where I would multiply with scalars and then horizontally concatenate. But this is so much simpler. Thanks

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by