how to modify the following code using quad

2 Ansichten (letzte 30 Tage)
Nicoleta
Nicoleta am 29 Okt. 2014
Bearbeitet: Star Strider am 29 Okt. 2014
function f=fun(x)
x=(-4:0.1:4);
y=x.^3-2*x.^2-5*x+6;
q=quad(fun,-4,4);
plot(x,q,'--r');
end
I was trying to compute and plot the integral for y=x.^3-2*x.^2-5*x+6 ;x>=-4 and x<=4. I used quad function in order to do that. I get the following error:
Undefined function or variable 'fun'.
Error in integralatema (line 4)
q=quad(fun,-4,4);
Can someone please tell me how can i modify the code in order to run it error-free? Thank you.

Antworten (1)

Star Strider
Star Strider am 29 Okt. 2014
If you want to call a function file you have to create a function handle for it with the ‘@’ operator. In the situation you illustrated, you would call it as
q = quad(@fun,a,b);
That said, do not call your function from inside your function! It would have created recursion problems even if it would have worked. (It wouldn’t have, because quad wants two limits for its integration, not a vector.)
So simply use quad with an anonymous function expression for your function, and your limits:
y= @(x) x.^3-2*x.^2-5*x+6; % Anonymous Function
q=quad(y, -4, 4); % Integrate
producing a value for ‘q’ of about -37.3.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by