简体   繁体   中英

How to calculate the value within a for loop in matlab

I have already made one equation but I need to find more generalized formula. My program is below:

p2=[];
W=3;
i=6;

for a1=1:W
    for a2=a1:W
        for a3=a2:W
            for a4=a3:W
                for a5=i-a4-a3-a2-a1;
                    if(a4 <= a5 && a5<=W)
                        p2=[p2;a1,a2,a3,a4,a5];
                    end
                end
            end
        end
    end
end

Here if a1=1 then a2=1,2,3 , if a1=2 then a2=2,3 and if a1=3 then a2=3 . The same condition is for a3 & a4 . Now I want to make this program only depends on W and i and I don't want to write a1 , a2 , a3 , a4 , a5 rather I just want to declare then a(1:5) . I have already tried but cannot get fruitful result.

Matlab experts I really need your help.

Thanks in advance.

I think this does what you want:

[a5 a4 a3 a2 a1]=ndgrid(1:W,1:W,1:W,1:W,1:W);
ind = find(a2>=a1&a3>=a2&a4>=a3&a5>=a4&a1+a2+a3+a4+a5==i)
p2 = [a1(ind) a2(ind) a3(ind) a4(ind) a5(ind)]

I assume you want to expand your code to large numbers so what I'm proposing might not be the best way. However, you could try to first enumerate all combinations of k=4 elements. For every combination, you could then calculate your 5th element according to your condition.

This approach is similar to the approach of Luis Mendo but avoids generating k**n possibilities. By taking all combinations and ordering them, you will have all valid sequences. You should interpret every combination (for example (2 1 2 1)) as one sequence (for example [1 1 2 2]). This allows you to avoid evaluating sequences like [2 1 1 2] as every combination is mapped on 1 valid sequence (and vice versa). You will not have to evaluate invalid sequences.

You can use combnk(v,k) to generate the combinations. You can then expand the found list with all possible values of a5.

For an arbitrary number of "a" variables, you can construct strings analogous to those of my previous solution and then eval those strings:

num = 5; % number of "a" variables
W = 3;
i = 6;

string1 = '[';
for n = num:-1:1
  string1 = [ string1 'a' num2str(n) ' '];
end
string1 = [ string1 '] = ndgrid(1:W);'];

string2 = 'ind = find(';
for n = 2:num
  string2 = [ string2 'a' num2str(n) '>=a' num2str(n-1) '&' ];
end
for n = 1:num
  string2 = [ string2 'a' num2str(n) '+'];
end
string2 = [ string2(1:end-1) '==i);' ];

string3 = 'p2 = [ ';
for n = 1:num
  string3 = [ string3 'a' num2str(n) '(ind) ' ];
end
string3 = [ string3 ']' ];

eval(string1);
eval(string2);
eval(string3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM