0

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
3
  • What is phi? Also: What output do you get, what would you expect instead? Commented Apr 9, 2015 at 17:42
  • i have updated my code check out the definition of phi in it.. Commented Apr 9, 2015 at 18:05
  • actually this is the haar approximation of a function and when we increase the value of j in the function that we have written the error(er in code) should decrease but instead it shows some random values being calculated and also it's increasing. Commented Apr 9, 2015 at 18:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@HemanshuSethi: If this solved your problem, please consider accepting my answer by clicking the grey check mark next so it turns green.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.