how to modify the following code using quad

조회 수: 2 (최근 30일)
Nicoleta
Nicoleta 2014년 10월 29일
편집: Star Strider 2014년 10월 29일
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