Reputation: 139
My code is for approximating functions using Haar wavelet for different levels of approximation. However when I try to calculate the error using the formula squareroot(integral(squareof(u(t)-uk(t)))) over the limits 0 to 1 where u(t) is the function f to be approximated uk(t) is the Haar approximation of the function until k terms However I'm not able to calculate the error properly due to some rogue matlab operation.Here's my code. The code for phi is
function a=phi(x)
if(0 <= x & x< 1)
a=1;
else
a=0;
end
function approxx(j)
f=@(x)sin(x);
b=@(j,t,k)phi((power(2,j)*t)-k);
a=@(x,j,k)(f(x).*b(j,x,k));
sum=@(x)0;
for k=0:power(2,j)
ak=integral(@(x)a(x,j,k),power(2,-j)*k,power(2,-j)*(k+1));
c=@(x)ak*power(2,j)*phi((power(2,j)*x)-k);
sum=@(x)(sum(x)+c(x));
end
fplot(f,[0,1],'r');hold on;
fplot(sum,[0,1]);
er=power(integral(@(x)power(f(x)-sum(x),2),0,1),0.5);
disp(er);
end
Upvotes: 0
Views: 92
Reputation: 6084
Your function phi
is not properly vectorized.
The call
integral(@(x)power(f(x)-sum(x), 2), 0, 1)
uses a vectorized integration method to compute the integral, i.e. it evaluates the function for a vector instead of a single value. sum(x)
for a vector x = linspace(0,1,100)
however returns a single double value instead of a vector of length 100. MATLAB thinks you want to subtract a single double value sum(x)==0
from the vector f(x)
and doesn't throw an error, but computes the wrong values instead.
You should replace phi
with it's correctly vectorized version:
function a=phi(x)
a = double(0<=x & x<1);
end
BTW: Consider directly computing the values instead of using nested anonymous functions. Those will get really really slow for large depth of nesting. Also sum
is a built-in function; you should refrain from naming your variables like built-ins.
Upvotes: 1