return iteration number from selected for loop value?

7 views (last 30 days)
I have a for loop that calculates distance that a projectile travels given different acceleration values. What I want is to return the iteration number, i, for a specified output. So for example, lets say I want to know which index value corresponds to dx=201.8842904397075. This answer would be i=3. If I input a value of dx or dy, I want to return the corresponding iteration, i, value.
vi = 23;
theta = 35;
phi = 10;
xnew = 44;
ynew = 33;
dz = 0 - 150;
v_z = -vi*sind(phi);
a(1) = 0;
ax(1) = a(1)*cosd(theta)*cosd(phi);
ay(1) = a(1)*sind(theta)*cosd(phi);
az(1) = a(1)*sind(phi) - 9.8;
v_zi = -vi*sind(phi);
dt(1) = (-sqrt(2*az(1)*dz + v_zi^2) + v_zi)/az(1);
vf(1) = vi + a(1)*dt(1);
v_xf(1) = vf(1)*cosd(theta)*cosd(phi);
v_yf(1) = vf(1)*sind(theta)*cosd(phi);
v_zf(1) = v_zi + az(1)*dt(1);
dx(1) = v_xf(1)*dt(1) + 0.5*ax(1)*dt(1)^2;
dy(1) = v_yf(1)*dt(1) + 0.5*ay(1)*dt(1)^2;
for i = 2:10
a(i) = a(i-1) + 1;
ax(i) = a(i)*cosd(theta)*cosd(phi);
ay(i) = a(i)*sind(theta)*cosd(phi);
az(i) = a(i)*sind(phi) - 9.8;
dt(i) = (-sqrt(2*az(i)*dz + v_zi^2) + v_zi)/az(i);
vf(i) = vi + a(i)*dt(i);
v_zf(i) = v_zi + az(i)*dt(i);
v_xf(i) = vf(i)*cosd(theta)*cosd(phi);
v_yf(i) = vf(i)*sind(theta)*cosd(phi);
dx(i) = v_xf(i)*dt(i) + 0.5*ax(i)*dt(i)^2
dy(i) = v_yf(i)*dt(i) + 0.5*ay(i)*dt(i)^2;
end
  1 Comment
Jan
Jan on 21 Aug 2017
Edited: Jan on 21 Aug 2017
It is useful to post the relevant part of the code only. As far as I can see, this would be enough to explain the problem:
for i = 1:20
dx(i) = rand + i;
end
Now find the position of a specific element.

Sign in to comment.

Accepted Answer

Jan
Jan on 21 Aug 2017
Edited: Jan on 21 Aug 2017
Find the index with the minimal distance of dx and a given value:
adx = 201.8842904397075;
[~, index] = min(abs(dx - adx));
If you know the value exactly without any rounding errors (and this is rarely the case):
index = find(dx == adx)

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!