MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by Suman Koirala on 17 Mar 2013

I am trying to find the time and distance at which the object is closest to the origin where the x and y coordinates vary with time. THis is what I have. But, something seems to be not working. First I used a point at time t=4 and used for loop to check for all times from 0 to 4.

disp('Finding the closest point') t=4; x=5*t- 10; y= (25*t^2)- 120*t+144; point =sqrt(x^2+y^2);

for t=0:0.1:4; x= 5.*t-10; y= 25.*t.^2- 120.*t+144; point1= sqrt(x^2+y^2); if point1<point xmin=x; ymin=y; tmin=t; end end

a= 5*tmin- 10; b= (25 *tmin^2)- 120*tmin +144; dist=sqrt(a^2+b^2); disp(dist) disp(tmin)

*No products are associated with this question.*

Answer by Cedric Wannaz on 17 Mar 2013

Edited by Cedric Wannaz on 18 Mar 2013

Accepted answer

This could be solved analytically, but if you want to do it numerically using the approach that you tried to implement, you could do the following:

>> t = 0:0.1:4 ; % Vector of all time steps. >> x = 5.*t-10 ; % Vector of all x values. >> y = 25.*t.^2- 120.*t+144 ; % Vector of all y values. >> d2 = x.^2 + y.^2 ; % Vector of all squared distances to origin.

>> id = find(d2 == min(d2)) % Index of the min. distance. id = 23 >> t(id) % Corresponding time. ans = 2.2000 >> x(id) % Corresponding x. ans = 1 >> y(id) % Corresponding y. ans = 1

>> plot(x, y) ; % Plot trajectory. >> axis([-1, 4, -1, 4]) ; % Zoom on region of interest. >> hold on ; >> plot(0,0,'Gx') ; % Add origin as a green cross. >> plot(x(id),y(id), 'Rx') ; % Add loc of the min as a red cross.

You will realize, however, that your approach can be dangerous if you lower the time step just a little, as the segment `OP` (where `P` is the estimate of the point realizing the min) will really be far from orthogonal to the curve.

## 0 Comments