How to speed up conv2 and finite difference method?

Hi, I would like to know if there is an opportunity to speed up a code listed below. Convolution method (CM) is a bit slower (40s) than iteration method(IM) (25s). Can this code (either or both methods) be improved further for speed? Note that Wnew and Znew are not exactly the same. (edges of matrix Znew are nonzero)
% iteration method
N=200;
Wold=zeros(N,N);
Wnew=zeros(N,N);
W=zeros(N,N);
Z=zeros(N,N);
Znew=zeros(N,N);
Zold=zeros(N,N);
W(10,10)=10;
Z(10,10)=10;
j = 2:N-1;
i = 2:N-1;
tic;
for time=0:0.1:100
Wnew(j,i)=a*(W(j+1,i)-4*W(j,i)+W(j-1,i)+W(j,i+1)+W(j,i-1))+2*W(j,i)-Wold(j,i);
% algorithm for display is here the same as for CM
Wold=W;
end
toc
% convolution method
D=[0 1 0; 1 -4 1; 0 1 0];
tic;
for time=0:1:100
Znew=2*Z-Zold+a*conv2(Z,D,'same');
% algorithm for display is here the same as for IM
Zold=Z;
end;
toc

5 Comments

Why do you have the two for loops here? The iterator is on time but you do not use that anywhere.
Thanks for reply, I added a correction to my original question. I added tic toc and location of display algorithm (plot etc). I am trying to compare the performance of both methods and to see if I can optimize further for speed for either of them.
Convolution can be speeded up by using an fft-based implementation in some cases, but it depends on the quantity of data. There is a crossover point beyond which the time taken to do the fft and ifft is outweighed by the faster operation of convolution in the frequency domain, but to know if it is worth it you would need to implement it and test the speed.
I will again ask the same thing. Why do you have the for loops there? You are running the same commands in a loop without any change.
Also you should use
doc profile
rather than tic toc if you seriously wish to optimise code.

Sign in to comment.

 Accepted Answer

After thorough testing, I decided not to use conv2 for my Finite difference method problem. An iterative method is simpler and a bit faster than conv2 method.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 5 May 2016

Answered:

on 6 May 2016

Community Treasure Hunt

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

Start Hunting!