photon
photon

Reputation: 616

MATLAB - Intersection of arrays

I am trying to graphically find the intersections between two surfaces and the x-y plane. (Intersection of surface z1 with the x-y plane and intersection z2 with the x-y plane)

I have created arrays representing the surfaces z1 = 3+x+y and z2 = 4-2x-4y and the z3 for the x-y plane using meshgrid. Looking everywhere, the only command that seems I can use to find the intersections between arrays is the intersect(A,B) command where A and B are arrays. When I enter intersect(z1,z3) however, I get the error "A and B must be vectors, or 'rows' must be specified." When I try intersect (z1,z2,'rows'), I am returned a 0-by-21 empty matrix. What am I doing wrong here?

My code:

x = -10:10;
y = -10:10;
[X,Y] = meshgrid(x,y);
z1 = 3+X+Y;
z2 = 4-2.*X-4.*Y;
z3 = 0.*X+0.*Y;         %x-y plane
surf(X,Y,z1)
hold on
surf(X,Y,z2)
surf(X,Y,z3)
int1 = intersect(z1,z3,'rows');
int2 = intersect(z2,z3,'rows');

Upvotes: 1

Views: 2394

Answers (2)

Rasman
Rasman

Reputation: 5359

a simple way (no major function calls) to solve this is as follows:

x = -10:.1:10;
y = -10:.1:10;
[X,Y] = meshgrid(x,y);
z1 = 3+X+Y;
z2 = 4-2.*X-4.*Y;
z3 = z1 - z2;
[~,mn] = min(abs(z3));

the intersection is defined as (x, y(mn)).

This, of course is a numerical approximation (since you wanted a numerical method), subject to boundary condition which I haven't explored (you'll need to disregard values far from zero when performing the minimum function)

Note: if you're looking for an equation, consider performing a least squares approximation on the resulting data.

Upvotes: 0

nicktruesdale
nicktruesdale

Reputation: 815

It sounds like you want the points where z1 = z2. To numerically find these, you have a couple options.

1) Numerical rootfinding: fsolve is capable of solving systems of equations. You can formulate the surfaces as functions of one vector, [x;y] and solve for the vector that makes the two surfaces equal. An example using the initial guess x=1, y=1 follows:

z1 = @(x) 3 + x(1) + x(2);
z2 = @(x) 4 - 2*x(1) - 4*x(2);
f = @(x) z1(x) - z2(x);

x0 = [1;1]
intersect = fsolve(@(x) f(x), x0);

2) Minimizing the error: If you are stuck with discrete data (arrays instead of functions) you can simply find the points where z1 - z2 is closest to zero. An easy starting point is to take the arrays Z1 and Z2 and find all points where the difference nears zero:

tol = 1e-3;
near_zero = abs(Z1 - Z2) < tol;

near_zero is going to be a logical array that is true whenever the difference between Z1 and Z2 is small relative to tol. You can use this to index into corresponding meshgrid arrays for X and Y to find the coordinates of intersection.

Upvotes: 3

Related Questions