Different variable multiplication for different columns in a MATRIX

조회 수: 1 (최근 30일)
NIRBAN CHAKRABORTY
NIRBAN CHAKRABORTY 2022년 4월 11일
답변: KuriGohan 2022년 4월 11일
Suppoose I have a (6*10) matrix name as A. Now i want to multiply the 1st 5 column with 2 and next 5 column with 3 of A matrix to develop a new B matrix. How I going to write that code of multiplication. PLease help me out in this.

답변 (3개)

Voss
Voss 2022년 4월 11일
A = randi(10,[6 10])
A = 6×10
7 5 7 3 1 2 9 8 3 6 3 3 4 8 8 1 7 9 8 2 9 1 2 5 1 1 3 1 1 5 7 7 1 7 1 3 5 10 2 10 3 7 6 10 7 8 1 6 4 3 9 10 10 9 1 6 2 7 3 4
% one way:
factor = [2*ones(1,5) 3*ones(1,5)]
factor = 1×10
2 2 2 2 2 3 3 3 3 3
B = A.*factor
B = 6×10
14 10 14 6 2 6 27 24 9 18 6 6 8 16 16 3 21 27 24 6 18 2 4 10 2 3 9 3 3 15 14 14 2 14 2 9 15 30 6 30 6 14 12 20 14 24 3 18 12 9 18 20 20 18 2 18 6 21 9 12
% another way:
factor = repelem([2 3],1,5)
factor = 1×10
2 2 2 2 2 3 3 3 3 3
B = A.*factor
B = 6×10
14 10 14 6 2 6 27 24 9 18 6 6 8 16 16 3 21 27 24 6 18 2 4 10 2 3 9 3 3 15 14 14 2 14 2 9 15 30 6 30 6 14 12 20 14 24 3 18 12 9 18 20 20 18 2 18 6 21 9 12

David Hill
David Hill 2022년 4월 11일
a=randi(10,5,10);
b=a.*([ones(1,5)*2,ones(1,5)*3]);

KuriGohan
KuriGohan 2022년 4월 11일
There is probably an easier way to do this; but this is what i would do:
a1 = a(:,1:5) .* 2;
a2 = a(:,6:end).*3;
b = vertcat(a1,a2);

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by