How to get every possible combinations of elements to approach a value and plot them together?

1 view (last 30 days)
I have, x = [144.2,31,138.8,56,54,27,25,24,18,17,12,4,266,240.5,215,132,75,30.3,20,19,18,18] and I would like a function to find all possible combinations to get the closest possible to a given value y.
For example if I give the value 325, I want to have in return the elements, " 144.2 138.8 24 18 (since 144.2+138.8+24+18=325) ; error=0 ; ", " 144.2 138.8 25 17 (since 144.2+138.8+25+17=325) ; error=0; ", and so on.
Or if I give the value 208, I want to have in return the elements, "56 132 20 (since 56+132+20=208) ; error=0; ", " 31 56 54 25 4 20 18 (since 31+56+54+25+4+20+18=208) ; error=0; ", and so on.
The process needs to comply with following conditions:
  • The combination to get the closest possible to a given value y but never more than y, always less or equal.
  • If more than one combination contains error=0; or and equal error, all the possible combinations will be provided.
  • Find the same for 0 to 325 and plot the closest value/s and it's error wrt y (0 to 325).
  2 Comments
Khalid Hassan
Khalid Hassan on 5 Jan 2021
I have tried this,
x = [144.2,31,138.8,56,54,27,25,24,18,17,12,4,266,240.5,215,132,75,30.3,20,19,18,18];
y = 325
X = [ x, -1;
-x, -1];
Y = [y; -y];
n = length(x);
f = [zeros(n,1); 1];
lo = [zeros(n,1); 0];
hi = [ones(n,1); Inf];
a = intlinprog(f, 1:n, X, Y, [], [], lo, hi);
keep = round(a(1:n))==1;
subx = x(keep)
sumsubx = sum(subx)
y
error = y - sumsubx
but the problem is, "error" is becoming negative in some cases, for example y=15, error=-1.which don't comply with 1st condition.

Sign in to comment.

Answers (1)

KSSV
KSSV on 5 Jan 2021
x = [144.2,31,138.8,56,54,27,25,24,18,17,12,4,266,240.5,215,132,75,30.3,20,19,18,18] ;
n = 3 ;
val = 325 ;
y = nchoosek(x,n) ;
thesum = sum(y,2) ;
idx = abs(thesum-val)<10^-2 ;
iwant = y(idx,:)
  5 Comments
Stephen23
Stephen23 on 5 Jan 2021
Given the requirement "...get the closest possible to a given value y but never more than y, always less or equal" using abs(..) does not help (hint: only positive or negative difference is useful for this task, you just need to think about which one).

Sign in to comment.

Categories

Find more on Simulink 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!