user1018331
user1018331

Reputation: 143

trapezodial rule matlab

I want to integrate "\int_{0}^{1}(exp(-int_{0}^{y}f(x)dx))dy" with my basic trapezoid algorithm. I recieve an error declaration, but I should define g as a function. Do you have any idea how to do it? Thanks a lot for any answer!

function y = trapapadbl(low1, up1,low2,up2,intstep1,intstep2,f)
g = 0;
step1 = (up1 - low1) / intstep1;
step2 = (up2 - low2) / intstep2;

for j = low1 : step1 : up1
    g = g + feval(f,j);
end
g = @(y)(g - (feval(f, low1) + feval(f, up1))/2) * step1;
for i = low2 : step2 : up2
    y= y + feval(g,i);
end
y= (y - (feval(g, low2) + feval(g, up2))/2) * step2;

Upvotes: 0

Views: 178

Answers (1)

alexplanation
alexplanation

Reputation: 1498

>> trapapadbl(0,1,0.1,0,1,0.1,@sin)

??? Undefined function or variable "y".

Error in ==> trapapadbl at 12
    y= y + feval(g,i);

Without working too hard to try to understand your code (!) the error is that y was never initialized. You can't add anything to y until it has a value. When I initialize y to 0, the code runs, but I get 0 as an output, which is not what happens when you integrate sin from 0 to 1. I may be calling the function wrong, but it's something to look out for!

Furthermore, your code is confusing, because you use the variable g as both a double (a number) and a function, even in the same line! The same problem happens as y is the input to your anonymous function, but also a double later on. It's syntactically correct, but a little hard to read. Consider using a different variable name, or including clear comments (or both!)

Upvotes: 2

Related Questions