Sum the elements of row vectors

조회 수: 4 (최근 30일)
Waseem AL Aqqad
Waseem AL Aqqad 2020년 11월 8일
댓글: Mathieu NOE 2020년 11월 9일
Hi,
How to let my code in every simulation run to check the sum of two row vectors and change some of the elements' values of the vector with the larger sum in case their sum of elements are not equal?
Say I have two row vectors, rowA and rowB with the same size but might have different sum of elements as I'm generaing them randomly.
rowA=[3 6 2 4 3 1 1 1 1 2 2 2 3 1 1 1 1 1 1 1]
rowB=[5 5 5 5 6 2 2 1 1 1 2 1 1 1 1 1 1 1 1 1]
% Constraint: sum(rowA) should equal sum(rowB). So, I want to change some the elements' values of the vector
% with the larger sum in order to satisfy this constraint but their sizes should remain
% the same.
% Perhaps, the code should replace some of the ones with zeros. As no. 1 will
% have the most frequent occurance in both vectors in each simulation run.

채택된 답변

Mathieu NOE
Mathieu NOE 2020년 11월 8일
hello
there are many ways you can change the vector content so the sums match
this is one possibility :
rowA=[3 6 2 4 3 1 1 1 1 2 2 2 3 1 1 1 1 1 1 1];
rowB=[5 5 5 5 6 2 2 1 1 1 2 1 1 1 1 1 1 1 1 1];
sA = sum(rowA,'all');
sB = sum(rowB,'all');
diff = sA - sB;
if diff<0 % decrease B
ind_non_zero = find(rowB>0);
ind_reduction = ind_non_zero(1:abs(diff));
rowB(ind_reduction) = rowB(ind_reduction)-1;
else
% do the symetrical for A
end
% check
sA2 = sum(rowA,'all');
sB2 = sum(rowB,'all');
diff2 = sA2 - sB2; % should always be zero now
  댓글 수: 2
Waseem AL Aqqad
Waseem AL Aqqad 2020년 11월 8일
That worked perfectly! Thank you very much, Mathieu.
Mathieu NOE
Mathieu NOE 2020년 11월 9일
you're welcome
have a great day

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by