How can I get the sums of all possible combinations of the values of a vector?

28 vues (au cours des 30 derniers jours)
Dear all,
I would like to get the sums of all unique possible combinations of the values of a vector.
For example:
Input:
A = [10 20 30]
Output:
B = [10 20 30 (10+20) (10+30) (20+30) (10+20+30)]
If possible, I would also like to get the indices of the values used to get the sum, so:
C = [1 2 3 (1,2) (1,3) (2,3) (1,2,3)]
The output does not necessarily have to be a vector.
The length of the input vector (A) will vary from iterations to iterations, so I'm looking for a way to calculate B and C based on a changing vector A
All help would be greatly appreciated!
  3 commentaires
Tom de van der Schueren
Tom de van der Schueren le 19 Août 2021
The values of vector B will later be used to see which sum comes closest to another given variable.
The indices of that closest sum will then be used in if statements, so a cellarray is probably preferable.
But at this moment I'm no able to construct either a vector with all the sums or a cellarray with the indices used to get these sums.
Adam Danz
Adam Danz le 19 Août 2021
Modifié(e) : Adam Danz le 19 Août 2021
Agreed, the cell array is the way to go. Simple indexing,
b(i)
c{i}
However, there could be multiple solutions to the problem you described. For example, a vector [1 2 3 4] will result in two values of 3 (3, 1+2), two values of 4 (4, 1+3), two values of five, two values of 6, and two values of 7. So if you're trying to find the closest value in b to some target value, there may be a problem.

Connectez-vous pour commenter.

Réponse acceptée

Adam Danz
Adam Danz le 19 Août 2021
% Input: v, a row or column vector
v = [2 4 6 8];
% create permutations and summation results
n = numel(v);
vIdx = 1:n;
results = cell(n,2);
for i = 1:n
results{i,1} = num2cell(nchoosek(vIdx,i),2)';
results{i,2} = sum(nchoosek(v,i),2)';
end
% Results
% b: 1xm row vector of summation results
% c: 1xm cell array of indicies of v for each summation
b = [results{:,2}]
b = 1×15
2 4 6 8 6 8 10 10 12 14 12 14 16 18 20
c = horzcat(results{:,1})
c = 1×15 cell array
{[1]} {[2]} {[3]} {[4]} {[1 2]} {[1 3]} {[1 4]} {[2 3]} {[2 4]} {[3 4]} {[1 2 3]} {[1 2 4]} {[1 3 4]} {[2 3 4]} {[1 2 3 4]}

Plus de réponses (0)

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!

Translated by