find points of intersection of 2 functions in matlab

To find the points of intersection of two functions in Matlab, you can follow these steps:

  1. Define the two functions using anonymous functions:
main.m
f = @(x) x.^2 + 2*x + 1;
g = @(x) -x.^2 + 4*x - 3;
51 chars
3 lines

Note: make sure the two functions have the same domain.

  1. Plot the two functions to see their intersection points visually:
main.m
x = linspace(-5, 5, 1000);
plot(x, f(x));
hold on;
plot(x, g(x));
grid on;
75 chars
6 lines
  1. Use the built-in fzero function to find the intersection points numerically:
main.m
h = @(x) f(x) - g(x);
x_intersect1 = fzero(h, -1);
x_intersect2 = fzero(h, 3);
79 chars
4 lines

Note: the fzero function finds a zero of a given function, which in this case corresponds to an intersection point of f and g.

  1. Display the intersection points:
main.m
fprintf('Intersection points:\n');
fprintf('(%.2f, %.2f)\n', x_intersect1, f(x_intersect1));
fprintf('(%.2f, %.2f)\n', x_intersect2, f(x_intersect2));
151 chars
4 lines

Here's the complete code:

main.m
% Define the two functions
f = @(x) x.^2 + 2*x + 1;
g = @(x) -x.^2 + 4*x - 3;

% Plot the two functions
x = linspace(-5, 5, 1000);
plot(x, f(x));
hold on;
plot(x, g(x));
grid on;

% Find the intersection points
h = @(x) f(x) - g(x);
x_intersect1 = fzero(h, -1);
x_intersect2 = fzero(h, 3);

% Display the intersection points
fprintf('Intersection points:\n');
fprintf('(%.2f, %.2f)\n', x_intersect1, f(x_intersect1));
fprintf('(%.2f, %.2f)\n', x_intersect2, f(x_intersect2));
476 chars
21 lines

gistlibby LogSnag