Sum the elements of row vectors

3 views (last 30 days)
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.

Accepted Answer

Mathieu NOE
Mathieu NOE on 8 Nov 2020
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 Comments
Waseem AL Aqqad
Waseem AL Aqqad on 8 Nov 2020
That worked perfectly! Thank you very much, Mathieu.
Mathieu NOE
Mathieu NOE on 9 Nov 2020
you're welcome
have a great day

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!