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
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
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
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
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
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 CenterFile 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!

Translated by