Alternative to for/while cycle

2 ビュー (過去 30 日間)
Luca Freilino
Luca Freilino 2019 年 4 月 10 日
コメント済み: Stephen23 2019 年 4 月 10 日
Hi, I have a question. I'm working at my master thesis and I'm writing a code quite computationally heavy. I'd like to light it and a possible option should be the replacement of the for and while cycles with another option. Do you have idea about any possible replacement?
This is a portion of the code (consider that the table_percentage matrix is already pre-allocated):
for a = ceil((minimum/single_step)+1):(length(steps)-((number_surrogates-1)*(minimum/single_step)))
for b = ceil((minimum/single_step)+1):(length(steps)-((number_surrogates-1)*(minimum/single_step)))
for c = ceil((minimum/single_step)+1):(length(steps)-((number_surrogates-1)*(minimum/single_step)))
for d = ceil((minimum/single_step)+1):(length(steps)-((number_surrogates-1)*(minimum/single_step)))
if steps(a)+steps(b)+steps(c)+steps(d)==1
table_percentage(index,:) = [steps(a), steps(b), steps(c), steps(d)];
index = index+1;
end
end
end
end
end
Thank you very much for every help.
Luca

採用された回答

Stephen23
Stephen23 2019 年 4 月 10 日
編集済み: Stephen23 2019 年 4 月 10 日
"a possible option should be the replacement of the for and while cycles with another option"
Why do you think that the loops themselves are the slow part? Have you profiled your code?
A quick look at your code shows that you could easily move the loop iteration vector definition before the loops, as it is indetical for all loops (currently you are pointlessly redefining exactly the same vector multiple times):
V = ceil((minimum/single_step)+1):(length(steps)-((number_surrogates-1)*(minimum/single_step)))
for a = V
for b = V
for c = V
for d = V
if steps(a)+steps(b)+steps(c)+steps(d)==1
table_percentage(index,:) = [steps(a), steps(b), steps(c), steps(d)];
index = index+1;
end
end
end
end
end
Another option would be to avoid the loops entirely using ndgrid to generate the indices:
[A,B,C,D] = ndgrid(steps(V));
X = [A(:),B(:),C(:),D(:)];
table_percentage = X(sum(X,2)==1,:);
Note that this method will only work for V with a small number of elements, and you will need to adjust the indexing to suit steps and table_percentage (which you have told us nothing about).

その他の回答 (1 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by