how to modify the following code using quad
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposte (1)
Star Strider
il 29 Ott 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.
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!