Iterative plot, stop when lines intersect.

16 views (last 30 days)
So I am trying to create a simulation that plots a path for one object up to another, stationary, object. The idea being that it uses the for loop below to plot each point in the path, checks whether it has intersected with the stationary line, then keeps plotting the original path until it does intersect, at which point it would stop.
I'm torn currently as to whether: it is working, but the distance between each plotted point isn't fine enough for it to ever match; or whether it doesn't actually work.
I've included in the code below the relevant variables, but haven't included any of the initial conditions that would give each variable its value. If the extra bits would help I'm happy to provide. "%Side1" is the object to be found, and "X1 and Y1" are the x and y of the line moving round (the "searching line"). Any help/clarification would be appreciated.
%Side 1
Side1x = [S1x S2x];
Side1y = [S1y S2y];
m1 = (S2y - S1y)/(S2x - S1x); %Gradient
c1 = S1y - S1x*m1; %Y-Intercept
%while loop to find object
Foundblock = false;
while Foundblock == false;
figure();
ylim([-1.5,1.5]); %Sets y range based on...
xlim([-1.5,1.5]); %Sets x range based on...
grid on; %Create a grid in the background of plot
hold on
plot(Side1x,Side1y,'b',Side2x,Side2y,'b',Side3x,Side3y,'b',Side4x,Side4y,'b');
i=1;
for i = 1:length(theta);
X1 = [x1o(i) x1i(i)];
Y1 = [y1o(i) y1i(i)];
h1o = plot(X1, Y1,'k','linewidth',0.1);
pause(0.0001);
delete(h1o);
b1x = x1i(i);
b1y = m1*b1x+c1;
if b1y == y1i(i);
Foundblock = true;
else
end
b1x = x1o(i);
b1y = m1*b1x+c1;
if b1y == y1o(i);
Foundblock = true;
else
end
end
end
hold off

Accepted Answer

Jos (10584)
Jos (10584) on 25 Oct 2017
Comparing two numbers is always tricky. I suggest to use a tolerance, so instead of
if x==y, ...
use
if (abs(x-y) < tol), ...
where tol is a value that you can define, based on the expected or needed precision of your data.
Furthermore, in your case you might want to check for a change in sign
signStart = x(1) - y
for i=2 ...
if sign(x(i)-y) signStart, ... % ha, a change in sign!
  1 Comment
Ethan Murray
Ethan Murray on 5 Nov 2017
Hi there,
just to say thanks for your answer, you helped solve it. Final code now looks like:
if b1x = x1i(i);
b1y = m1*b1x+c1;
if abs(b1y - y1i(i)) < tol;
Foundblock = true;
break
else
end
end
Where 'tol' is, as you've said, a tolerance value. and it works perfectly.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!