How can I make a for loop faster ?
2 ビュー (過去 30 日間)
古いコメントを表示
Considering that I have a matrix p (m x n) and a for loop like this:
for i = 2:Nx
for j = 2:Nz
PE = a*p(i,j)+b*p(i-1,j)+c*p(i+1,j) +d*p(i,j+1)+e*p(i,j-1);
p(i,j) = (1-Constant)*PE + Constant*PE
end
end
Where Nx are the lines minus 1 and Nz the columns minus 1. The problem is that to calculate the next p(i,j) I need the previous one, so I do not know how to vectorize this operation. (a,b,c,d,e are constants). I really appreciate any help. Thank you.
2 件のコメント
Guillaume
2017 年 11 月 8 日
編集済み: Guillaume
2017 年 11 月 8 日
The bigger problem is that p(i,j) also depends on future, not yet calculated values (since you have i+1 and j+1 in your expression). How is that supposed to work?
edit: Hopefully the two Constant terms are actually different constants otherwise p(i,j) is simply PE.
Kaushik Lakshminarasimhan
2017 年 11 月 8 日
This looks like a smoothing operation. Perhaps the OP already has an Nx+1 x Nz+1 matrix p and wants to modify it? Although that is not apparent from the wording in the question.
回答 (1 件)
Walter Roberson
2017 年 11 月 8 日
Is this a Finite Element Mesh code? If so then the flow should be like
new_p = p; %to get the right size and to copy the edge values
for i = 2:Nx
for j = 2:Nz
PE = a*p(i,j)+b*p(i-1,j)+c*p(i+1,j) +d*p(i,j+1)+e*p(i,j-1);
new_p(i,j) = (1-Constant)*PE + Constant*PE
end
end
p = new_p;
And this is vectorizable.
Your existing code is quite order dependent, which would not be the case for finite element mesh.
2 件のコメント
Guillaume
2017 年 11 月 8 日
Ah, but that is a very different operation to what is in the OP question. Elements of new_p do not depends on each others.
If that is the desired operation then it is a simple convolution or correlation that can be achieved with conv2 or filter2.
Walter Roberson
2017 年 11 月 8 日
My working hypothesis is that the author was reading off the definition of how to update nodes without realizing that the updated versions should depend only on the previous versions, not on what is being computed as it is running through the matrix.
conv2 is a good idea for processing the situation if my hypothesis is correct.
参考
カテゴリ
Help Center および File Exchange で Quadratic Programming and Cone Programming についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!