Using fzero for intesection and "integral" for area calculation

5 views (last 30 days)
I'm trying to caluclate the area between the curves from about x=-0.22 and 4 as the intersection happens about in those two places. However having trouble using fzero to find the correct intersects and using "integral" to calculate the area.
clear, clc, clear plot
format short
g=@(x)exp((-x.^2)./2);
h=@(x) x.^2-4.*x;
x=linspace(-1,5,100);
plot(x,g(x));
hold on
plot(x,h(x));
z(1)=fzero(g,-0.22); % dont know how to use
z(2)=fzero(h,4); % dont know how to use
% integral
a=z(1);
b=z(2);
f=@(x) % dont know how to use
q=integral(f,a,b)

Accepted Answer

Stephan
Stephan on 24 Jan 2021
clear, clc, clear plot
format short
g=@(x)exp((-x.^2)./2);
h=@(x) x.^2-4.*x;
f=@(x) g(x) - h(x);
x=linspace(-1,5,100);
plot(x,g(x));
hold on
plot(x,h(x));
z(1)= fzero(f,-0.22);
z(2)= fzero(f,4)
% % integral
a=z(1);
b=z(2);
q=integral(f,a,b)

More Answers (2)

John D'Errico
John D'Errico on 24 Jan 2021
Edited: John D'Errico on 24 Jan 2021
g=@(x)exp((-x.^2)./2);
h=@(x) x.^2-4.*x;
x=linspace(-1,5,100);
plot(x,g(x));
hold on
plot(x,h(x));
You did that much correctly.
Now, you want to find the INTERSECTION point of the two curves. That is, you want to know where the curves have the same y value? Is that not where g(x) == h(x)?
Using fzero on g alone will not help you! What is the root that fzero can find that will help? How about this? If we want to find the point where g==h, then what if we solve for the point where (g(x)-h(x))==0?
fzero(@(x) g(x) - h(x),-0.2)
Once you have done this for BOTH intersections, now what area do you want to find? You want to find the area of g(x) - h(x), since in that interval, g(x) is greater than h(x).

Steven Lord
Steven Lord on 24 Jan 2021
clear, clc, clear plot
Use these commands sparingly or not at all in a script file. People running your script may not expect a program that's supposed to compute the integral of an area to destroy all the variables in their workspace and clear their command window.
format short
g=@(x)exp((-x.^2)./2);
h=@(x) x.^2-4.*x;
x=linspace(-1,5,100);
plot(x,g(x));
hold on
plot(x,h(x));
% Adding in the line at y = 0 for reference
yline(0, ':')
z(1)=fzero(g,-0.22); % dont know how to use
z(2)=fzero(h,4); % dont know how to use
You don't want zeros of g and h. If you were to zoom in you'd see that g never quite reaches 0 over the interval [-1, 5]. You want to find points x where g(x) = h(x), right? Rewrite that expression and you will realize what you need to pass into fzero. [If you're not sure after rewriting it, read the description of the fun input on the fzero documentation page.]
%{
% integral
a=z(1);
b=z(2);
f=@(x) % dont know how to use
The expression you used in computing z(1) and z(2) will be useful here.
q=integral(f,a,b)
%}

Community Treasure Hunt

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

Start Hunting!