return iteration number from selected for loop value?

2 vues (au cours des 30 derniers jours)
Andrew Poissant
Andrew Poissant le 21 Août 2017
Modifié(e) : Jan le 21 Août 2017
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 commentaire
Jan
Jan le 21 Août 2017
Modifié(e) : Jan le 21 Août 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.

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 21 Août 2017
Modifié(e) : Jan le 21 Août 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)
  1 commentaire
Andrew Poissant
Andrew Poissant le 21 Août 2017
ah, very clever! Thank you, works like a charm!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by