How can I make a for loop faster ?

2 Ansichten (letzte 30 Tage)
Gabriel Rodrigues
Gabriel Rodrigues am 8 Nov. 2017
Kommentiert: Walter Roberson am 8 Nov. 2017
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 Kommentare
Guillaume
Guillaume am 8 Nov. 2017
Bearbeitet: Guillaume am 8 Nov. 2017
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
Kaushik Lakshminarasimhan am 8 Nov. 2017
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Walter Roberson
Walter Roberson am 8 Nov. 2017
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 Kommentare
Guillaume
Guillaume am 8 Nov. 2017
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 am 8 Nov. 2017
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Probability Distributions and Hypothesis Tests finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by