Sum the elements of row vectors
조회 수: 4 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!