Monique
Monique

Reputation: 31

Matlab integration

I wrote a code in matlab to compute an integral using Gauss-Chebyshev quadrature , but it doesn't work:

function int = chebquad('-1i*exp(x+3)',1e-8,-1,1); 
f=inline('-1i*exp(x+3)','x')  
old_int = inf; 
for n=1:1000    
    x = cos(((2*(1:n) - 1)/(2*n))*pi);    
    w = pi/n;    
    fx = f(x);    
    int = sum(w.*fx);    
    if abs(int_old-int) < tol 
        break    
    end    
    old_int = int;   
end

Any suggestions?

Thanks!!

Upvotes: 0

Views: 1733

Answers (2)

Rasman
Rasman

Reputation: 5359

for future reference, it would help us out that you didn't display your function with the specified variable as constants:

so show:

function hv= someName(firstVar, secondVar)

and not:

function hv= someName(1, 'some string')

I don't know why you have both -1 and 1, but I'm assuming tol = 1e-8. That being said, you made a small mistake in your code by using int_old instead of old_int.

Edit: so at first I thought, you just displayed the function for "our benefit", now I think you didn't even define a Matlab function properly. Please read this and learn about basic Matlab coding. Chebyshev–Gauss quadrature is defined over -1 to 1, and thus doesn't need to be in a function code, below is the revised code:

function intV = chebquad(funC,tol)

f=inline(funC,'x');
old_int = inf; 
for n=1:1000    
    x = cos(((2*(1:n) - 1)/(2*n))*pi);    
    w = pi/n;    
    fx = f(x);    
    intV = sum(w.*fx);    
    if abs(old_int - intV) < tol 
        break    
    end    
    old_int = intV ;   
end

at the command prompt, you call this with:

intV = chebquad('-1i*exp(x+3)', 1e-8)

Upvotes: 2

duffymo
duffymo

Reputation: 308988

It helps to know the answer and what the function looks like before you start. Here's what Wolfram Alpha says about your function:

http://www.wolframalpha.com/input/?i=+-i+*exp%28x%2B3%29%2Fsqrt%281-x%5E2%29

And here's what the answer should be:

http://www.wolframalpha.com/input/?i=int++-i+*exp%28x%2B3%29%2Fsqrt%281-x%5E2%29%2C+x%3D-1..1

See if that helps.

Upvotes: 0

Related Questions