Sum the elements of row vectors
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Waseem AL Aqqad
le 8 Nov 2020
Commenté : Mathieu NOE
le 9 Nov 2020
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 commentaires
Réponse acceptée
Mathieu NOE
le 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!