0
votes

I drew a stair plot in matlab with different points. I wanna find point of intersection in the plot.

The first plot:

a = [0 30 50 60 70];
s = [4 5 9 10 13];
sum_a = zeros(1,length(a));
sum_a = a(1);
for i=2:length(a)
    sum_a(i) = sum_a(i-1) + a(i); 
end

The second plot:

x = [0 40 30 20 10];
b = [10 8 6 4 2];
sum_x = zeros(1,length(x));
sum_x = x(1);
for i=2:length(x)
    sum_x(i) = sum_x(i-1) + x(i);
end

stairs(sum_x, b)
hold on
stairs(sum_a, s , 'r')

Now, How to find intersection between two plot?

1

1 Answers

1
votes

I separated each plot into horizontal and vertical lines and checked for pairwise intersections between horizontal lines of one plot and vertical lines of the other, and vice versa:

% vertical lines of each graph
vlines1 = [sum_x(2:end);b(1:end-1);b(2:end)].';
vlines2 = [sum_a(2:end);s(1:end-1);s(2:end)].';
% horizontal lines of each graph
hlines1 = [sum_x(1:end-1);sum_x(2:end);b(1:end-1)];
hlines2 = [sum_a(1:end-1);sum_a(2:end);s(1:end-1)];
% crossing function - h.line's y value between v.line y values and the
% same with x.
intfun = @(hl,vl) (hl(1,:) <= vl(:,1)) & (hl(2,:) >= vl(:,1)) & (hl(3,:) >= vl(:,2)) & (hl(3,:) <= vl(:,3));
% check intersections
int1 = intfun(hlines1,vlines2);
int2 = intfun(hlines2,vlines1);
% find intersections points
[r1,c1] = find(int1);
[r2,c2] = find(int2);
% find intersections coordinate(s)
y = [hlines1(3,c1),hlines2(3,c2)].';
x = [vlines2(r1,1);vlines1(r2,1)];
plot(x,y,'xk','MarkerSize',30,'LineWidth',2)

if intfun doesn't work in older MATLAB versions you can use this instead:

intfun = @(hl,vl) bsxfun(@le,hl(1,:),vl(:,1)) & bsxfun(@ge,hl(2,:),vl(:,1))...
    & bsxfun(@ge,hl(3,:),vl(:,2)) & bsxfun(@le,hl(3,:),vl(:,3));

enter image description here