Sum the elements of row vectors
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Waseem AL Aqqad
el 8 de Nov. de 2020
Comentada: Mathieu NOE
el 9 de Nov. de 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 comentarios
Respuesta aceptada
Mathieu NOE
el 8 de Nov. de 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 comentarios
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!