%area
clear all;
syms x;
% Define the two functions
f = x^4 - 4*x^2 + 4; % First curve: f(x) = x^4 - 4*x^2 + 4
g = x^2; % Second curve: g(x) = x^2
% 1. Find points of intersection
intersection_points = solve(f == g, x); % Solve for the intersection points
intersection_points = double(intersection_points); % Convert symbolic to numeric
% Display intersection points
disp('Intersection points:');
disp(intersection_points);
% 2. Initialize total area
total_area = 0;
% Loop over each interval between consecutive intersection points
for i = 1:length(intersection_points)-1
% Midpoint of the current interval
mid_point = (intersection_points(i) + intersection_points(i+1)) / 2;
% Evaluate the functions at the midpoint to determine which is on top
f_mid = double(subs(f, x, mid_point));
g_mid = double(subs(g, x, mid_point));
if f_mid > g_mid
top_function = f;
bottom_function = g;
else
top_function = g;
bottom_function = f;
end
% 3. Compute the area for this interval
area = int(top_function - bottom_function, x, intersection_points(i), intersection_points(i+1));
area_value = double(area);
% Add this area to the total
total_area = total_area + area_value;
end
% Display the total area of the common region
fprintf('Total area of the common region: %.5f\n', total_area);
% 4. Plot the curves and the shaded regions
figure;
fplot(f, [intersection_points(1)-1, intersection_points(end)+1], 'b-', 'LineWidth', 2); hold on;
fplot(g, [intersection_points(1)-1, intersection_points(end)+1], 'r-', 'LineWidth', 2);
% Shade the regions between the curves
for i = 1:length(intersection_points)-1
x_vals = linspace(intersection_points(i), intersection_points(i+1), 1000);
% Recalculate which function is on top for the current interval
mid_point = (intersection_points(i) + intersection_points(i+1)) / 2;
f_mid = double(subs(f, x, mid_point));
g_mid = double(subs(g, x, mid_point));
if f_mid > g_mid
y_top = double(subs(f, x, x_vals));
y_bottom = double(subs(g, x, x_vals));
else
y_top = double(subs(g, x, x_vals));
y_bottom = double(subs(f, x, x_vals));
end
% Fill the region between the curves
fill([x_vals, fliplr(x_vals)], [y_top, fliplr(y_bottom)], 'g', 'FaceAlpha', 0.3);
end
% legend('f(x) = x^4 - 4x^2 + 4', 'g(x) = x^2', 'Common Region');
% xlabel('x');
% ylabel('y');
% title('Area of the Common Region Between Two Curves');
% grid on;
% hold off;
Cite As
Kirubahari (2024). AREA BETWEEN TWO GRAPH (https://www.mathworks.com/matlabcentral/fileexchange/173350-area-between-two-graph), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Created with
R2024b
Compatible with any release
Platform Compatibility
Windows macOS LinuxTags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
Version | Published | Release Notes | |
---|---|---|---|
1.0.0 |