return iteration number from selected for loop value?

조회 수: 2 (최근 30일)
Andrew Poissant
Andrew Poissant 2017년 8월 21일
편집: Jan 2017년 8월 21일
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
Jan
Jan 2017년 8월 21일
편집: Jan 2017년 8월 21일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 8월 21일
편집: Jan 2017년 8월 21일
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)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by