Optimize code without for loop

2 ビュー (過去 30 日間)
Marc Servagent
Marc Servagent 2023 年 7 月 31 日
移動済み: Stephen23 2024 年 9 月 26 日
My code uses 6 nested for loops, it is basically used to build 3D matrix with data in specific order from 2D matrix with data in random order.
These lines work as expected but take significant times to execute.
Is there any alternative approach of programming which lead to avoid all these for loops and therefore speed up the execution ?
for z=1:1001
p=0;
for j=1:length(DOFNameRef)
for n=1:length(DOFDir)
for i=1:length(DOFNamePoint)
for l=1:length(DOFDir)
p = p+1;
for k=1:Mlig*Mcol
c(k) = contains(Resp(k),DOFNamePoint(i)) && contains(Resp(k),DOFDir(l)) && contains(Ref(k), DOFNameRef(j)) && contains(Ref(k),DOFDir(n));
end
[NumLigne, NumCol] = NLignNCol(p,Mlig, Mcol);
M(NumLigne,NumCol,z) = Data(z, c);
end
end
end
end
end

採用された回答

Abhinaya Kennedy
Abhinaya Kennedy 2024 年 9 月 24 日
You can consider:
  • Vectorization: Try to replace loops with vectorized operations. Eg., you can use logical indexing instead of the contains function inside the innermost loop.
  • Preallocation: Preallocate all matrices and arrays before the loops. This avoids dynamically resizing arrays, which is computationally expensive.
  • Parallel Computing: If you have the Parallel Computing Toolbox, you can use parfor to parallelize the outer loops.
  • Logical Indexing: Instead of using nested loops to find elements that meet certain conditions, use logical indexing.
  1 件のコメント
Marc Servagent
Marc Servagent 2024 年 9 月 26 日
移動済み: Stephen23 2024 年 9 月 26 日
Thanks,
the vectorization helped to sigificantly improve the situation.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by