For loop Nested Loop

1 回表示 (過去 30 日間)
ben
ben 2012 年 10 月 12 日
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???

回答 (2 件)

Teja Muppirala
Teja Muppirala 2012 年 10 月 12 日
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 件のコメント
ben
ben 2012 年 10 月 12 日
編集済み: Walter Roberson 2012 年 10 月 12 日
Hi Teja
Thank you for giving the comment. I've been tried the ga function but what my goal is to get the optimal maximum of func_A . It seems the ga function can't guarantee to get the optimal solution.
Jan
Jan 2012 年 10 月 12 日
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
Walter Roberson 2012 年 10 月 12 日
Change your line
for k=0:11.^12-1
to
for k = uint64(0) : uint64(11) .^ 12 - uint64(1)
  1 件のコメント
Walter Roberson
Walter Roberson 2012 年 10 月 12 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by