Asked by SATHYA PRIYA SUGUMAR
on 11 Nov 2019 at 9:41

Hi all,

I have two curves and I need to find and count the number of times they intersect. Is there any matlab function to do so?

Answer by Dimitris Kalogiros
on 11 Nov 2019 at 10:37

Edited by Dimitris Kalogiros
on 11 Nov 2019 at 13:47

If you have two functions y=f(t) and y=g(t) you can find their intersections by solving the equation f(t)=g(t). But such a thing (maybe) should be an impossible task.

So, here you are a more general approach

clearvars;

clc;

syms t f(t) g(t)

%define functions

f(t)=(t^2)+3*sin(2*pi*t)-2

g(t)=exp((1/2)*t)

%plot the functions

fplot(f(t)); hold on;

fplot(g(t));

%refine plot

grid on;

legend('f', 'g');

ax = gca;

ax.YAxisLocation='origin';

ax.XAxisLocation='origin';

%determine intersections

downLimit=-5; upperLimit=5; %area of searching

dt=0.1; % accuracy step (it should be small enough)

rootCounter=0;

h(t)=f(t)-g(t);

for t=downLimit:dt:upperLimit

if h(t)==0 %f(t)=g(t)

rootCounter=rootCounter+1;

elseif h(t)*h(t+dt)<0 % f(to)=g(to), t<to<t+dt

rootCounter=rootCounter+1;

end

end

fprintf('found %d roots', rootCounter);

Dimitris Kalogiros
on 11 Nov 2019 at 16:15

.... and here you are what you get, when you run this code

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Dimitris Kalogiros (view profile)

## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/490390-count-the-number-of-intersections-between-any-two-curves#comment_765923

## SATHYA PRIYA SUGUMAR (view profile)

## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/490390-count-the-number-of-intersections-between-any-two-curves#comment_765926

Sign in to comment.