Info

This question is closed. Reopen it to edit or answer.

Below I have stated both my 'original code' and its corresponding 'vectorized code' for the series approximation of Error function, but I'm getting wrong results by evaluating my 'vectorized code'. Please help.

1 view (last 30 days)
%%original code z=-2:0.001:2; sm=0; N=200; format long; f_ans=zeros(1,length(z)); for k=1:length(z) sm=0; for n=0:N q=(((-1)^n*(z(k).^(2*n+1)))/(gamma(n+1)*(2*n+1))); sm=sm+q; end f_ans(k)=((2/sqrt(pi))*sm); end
%%vectorized code z=-2:0.001:2; N=200; %Initialization E4=zeros(length(z),(N+1)); E4_f=zeros(1,length(z)); arr1=zeros(length(z),(N+1)); arr2=zeros(length(z),(N+1)); arr3=zeros(length(z),(N+1)); arr4=zeros(length(z),(N+1));
%Cal numerator arr arr1a=(-1)*ones(1,length(z)); arr1b=0:200; arr1= [bsxfun(@power,arr1a,arr1b')]'; arr1c=z; arr1d=2.*[0:200]+1; arr2= [bsxfun(@power,arr1a,arr1b')]'; arr3= arr1.*arr2;
%Cal denominator arr arr4=gamma([0:200]+1).*(2.*[0:200]+1);
%division E4=bsxfun(@rdivide,arr3,arr4);
%perform summation E4_f=sum(E4,2)';

Answers (1)

Are Mjaavatten
Are Mjaavatten on 14 Apr 2017
The best way to debug a program with large arrays is to reduce the size of the problem so that arrays are small enough to easily inspect. This makes it much easier to spot the errors in your logic. In your case, choose for instance z = [-1.0.1] and N = 4.
You will find that your basic approach is sound, but you use the wrong arrays in the expression for arr2.
A corrected version of the vectorized code runs about 60 times faster that the loop version om my PC. (The built-in erf function runs 200 times faster still.)

Community Treasure Hunt

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

Start Hunting!