how to modify the following code using quad

2 次查看(过去 30 天)
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.

回答(1 个)

Star Strider
Star Strider 2014-10-29
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by