How to fast determine all possible solutions for such a+b+c+d+...+n=x?
I have values which are in four seperate vectors such as:
toplam1 % 1x1000 double
toplam2 % 1x1000 double
toplam3 % 1x1000 double
toplam4 % 1x1000 double
I need to find the highest sum value of toplam(a) + toplam(b) + toplam(c) + toplam(d) for a + b + c + d = 1000 condition. For instance the solution might be like this: toplam1(120) + toplam2(80) + toplam3(500) + toplam4(300) where 120+80+500+300=1000.
First of all I've tried to determine the all possible solutions of a+b+c+d=1000 equation:
cond = 1000; %preallocation for faster solution preAll = (cond-10)^3; %3 nested loops kayit1 = zeros(1, preAll); kayit2 = zeros(1, preAll); kayit3 = zeros(1, preAll); kayit4 = zeros(1, preAll);
a=1; b=1; c=1; m=1;
for i=1:cond
    for ii=1:cond
        for iii=1:cond
            d = 1000-a-b-c;
            kayit1(m) = a;
            kayit2(m) = b;
            kayit3(m) = c;
            kayit4(m) = d;
            c=c+1;
            m=m+1;
        end
        b=b+1;
        c=1;
    end
    a=a+1;
    b=1;
    c=1;
end
My main problem is, this code takes too much time to evaulate and when it is done it gaves 970 billions values which need to be examined. To find the highest sum I have used this code:
vals= zeros(1,preAll);
m=1;
for i=1:preAll
    vals(m) = toplam1(kayit1(m))+toplam2(kayit2(m))+toplam3(kayit3(m))+toplam4(kayit4(m));
    m=m+1;
    i=i+1;
end
[val1, index1] = max(vals); %After finding the index1, I should be able to determine a,b,c and d.
This code gives "subscript indices must either be real positive integers or logicals." error because of exceeding integer value of i I guess.
So, is there better/faster solution for such equations like a+b+c+d+...+n=x or another approach to find highest sum?
1 comentario
Respuestas (2)
0 comentarios
0 comentarios
Ver también
Categorías
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!