For loop Nested Loop
2 views (last 30 days)
Show older comments
I just want to solve the problem by using the brute force method. Here is the pseudo code:
for i=1:11
for j=1:11
for k=1:11
.
.
.
Variable=[i j k l m n o p q r s t];
Result=func_A(Variable);
end
end
end
There are 12 variables and each variable is greater than or equal to one and less than or equal to
11(1<=x<=11). Each integer combination will have a result value.
I want to get the maximum of func_A.
I have been trying to solve by this way:
b=[11:-1:0];
c=11.^b;
for k=0:11.^12-1
d=floor(k./c);
a=mod(d,11)+1;
result=func_A(a);
end
but here is the error message from matlab
FOR loop index is too large. Truncating to 2147483647.
Does there have a clever way to speed up the for loop???
0 Comments
Answers (2)
Teja Muppirala
on 12 Oct 2012
Why do you want to do this by brute force? You will have to test 12^11 combinations, which is quite a lot. I don't know what your func_A is, but even if it only takes 1 microsecond to do one evaluation, testing all possible combinations will take at least 12^11 * 1e-6 / 3600 / 24 = 8.5 days (assuming no parallel processing).
Why not try a more practical optimization method, such as Genetic Algorithm?
3 Comments
Jan
on 12 Oct 2012
11^12 / (86400 * 365 * 1000). This means that a brute search will consume 99 years, if you can check 1000 vectors per second. So if you really need the guaranteed optimal solution, you need some time. A parallelization is possible: If you can run this on 100 computers with 4 cores, the result will be found in some month.
Walter Roberson
on 12 Oct 2012
Change your line
for k=0:11.^12-1
to
for k = uint64(0) : uint64(11) .^ 12 - uint64(1)
1 Comment
Walter Roberson
on 12 Oct 2012
For an alternate code formulation that might be clearer (but not necessarily any faster), see http://www.mathworks.co.uk/matlabcentral/answers/29662-generate-points-sorted-by-distance#comment_63935
What are the characteristics of the function you are trying to maximize? It could be that by knowing something about the function, optimizations could be made.
Also, could the function be rewritten to be vectorized to some degree? The overhead of calling the function each time will add up to quite a lot. Could it perhaps be vectorized a fair bit? If so then usually maximum speed would be from vectorizing as much as will fit into memory at a time.
See Also
Categories
Find more on Loops and Conditional Statements 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!