kneedhelp
kneedhelp

Reputation: 655

How to find the intersection of two ellipses in MATLAB

I have two equations:

ellipseOne = '((x-1)^2)/6^2 + y^2/3^2 = 1';

and

ellipseTwo = '((x+2)^2)/2^2 + ((y-5)^2)/4^2 = 1';

and I plotted them:

ezplot(ellipseOne, [-10, 10, -10, 10])
hold on
ezplot(ellipseTwo, [-10, 10, -10, 10])
title('Ellipses')
hold off

Now I'm trying to find the intersection of the two ellipses. I tried:

intersection = solve(ellipseOne, ellipseTwo)
intersection.x
intersection.y

to find the points where they intersect, but MATLAB is giving me a matrix and an equation as an answer which I don't understand. Could anyone point me in the right direction to get the coordinates of intersection?

Upvotes: 3

Views: 4219

Answers (1)

rayryeng
rayryeng

Reputation: 104464

The solution is in symbolic form. The last step you need to take is to transform it into numeric. Simply convert the result using double. However, because this is a pair of quadratic equations, there are 4 possible solutions due to the sign ambiguity (i.e. +/-) and can possibly give imaginary roots. Therefore, isolate out the real solutions and what is left should be your answer.

Therefore:

% Your code
ellipseOne = '((x-1)^2)/6^2 + y^2/3^2 = 1';
ellipseTwo = '((x+2)^2)/2^2 + ((y-5)^2)/4^2 = 1';
intersection = solve(ellipseOne, ellipseTwo);

% Find the points of intersection
X = double(intersection.x);
Y = double(intersection.y);
mask = ~any(imag(X), 2) | ~any(imag(Y), 2);
X = X(mask); Y = Y(mask);

The first three lines of code are what you did. The next four lines extract out the roots in numeric form, then I create a logical mask that isolates out only the points that are real. This looks at the imaginary portion of both the X and Y coordinate of all of the roots and if there is such a component for any of the roots, we want to eliminate those. We finally remove the roots that are imaginary and we should be left with two real roots.

We thus get for our intersection points:

>> disp([X Y])
   -3.3574    2.0623
   -0.2886    2.9300

The first column is the X coordinate and the second column is the Y coordinate. This also seems to agree with the plot. I'll take your ellipse plotting code and also insert the intersection points as blue dots using the above solution:

ezplot(ellipseOne, [-10, 10, -10, 10])
hold on
ezplot(ellipseTwo, [-10, 10, -10, 10])
% New - place intersection points
plot(X, Y, 'b.');
title('Ellipses');
hold off;

enter image description here

Upvotes: 7

Related Questions