Code not working, something with while loop

조회 수: 3 (최근 30일)
Zach Harrison
Zach Harrison 2021년 4월 16일
댓글: Zach Harrison 2021년 4월 16일
I think the error in my code is in the while loop, I don't think i and/or j are increasing their value.
E_n is the value that will give my my answer. I want i and j to start at 1, but when I do, E_n is 0 for all values. Then when I change the starting conditions, only a few numbers are non-zero, and they are all the same value. This is why I think my while loops are not working, which leads to my code not checking every element in the matrix M.
M_0 = [0, 30, 90, 135, 180, 200, 350;
0, 30, 90, 135, 180, 200, 350;
0, 30, 90, 135, 180, 200, 350;
0, 30, 90, 135, 180, 200, 350];
M = M_0 .* (pi / 180);
e = [0.01;
0.1;
0.5;
0.9];
% Initial Calculations
E = zeros(4,7);
error = 10;
i = 1;
j = 1;
while j <= 4
while i <= 7
if M(j,i) > -pi && M(j,i) < 0
E_n = M(j,i) - e(j);
elseif M(j,i) > pi
E_n = M(j,i) - e(j);
elseif M(j,i) < pi && M(j,i) > 0
E_n = M(j,i) + e(j);
else
E_n = M(j,i);
end
while error >= 10^-6
E_n_plus_1 = E_n + ((M(j,i) - E_n + e(j) * sin(E_n)) / (1 - e(j) * cos(E_n)));
error = abs(E_n - E_n_plus_1);
E_n = E_n_plus_1;
end
E(j,i) = E_n_plus_1;
i = i + 1;
end
j = j + 1;
end
M_deg = reshape(M_0,28,1);
E_deg = reshape(E,28,1);
e1 = [0.01;0.01;0.01;0.01;0.01;0.01;0.01;
0.1;0.1;0.1;0.1;0.1;0.1;0.1;
0.5;0.5;0.5;0.5;0.5;0.5;0.5;
0.9;0.9;0.9;0.9;0.9;0.9;0.9];
table(M_deg,e1,E_deg)
  댓글 수: 1
Zach Harrison
Zach Harrison 2021년 4월 16일
편집: Zach Harrison 2021년 4월 16일
Update: i and j values are 8 and 5 respectively and the end of the code so I guess that part works fine

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

채택된 답변

David Fletcher
David Fletcher 2021년 4월 16일
편집: David Fletcher 2021년 4월 16일
The counter for the inner i loop never gets reset back to it's initial value, so it will only run on the first iteration of the j loop. You will incidentally have the same problem with the error loop, as that never gets re-initialised after the loop either
  댓글 수: 3
David Fletcher
David Fletcher 2021년 4월 16일
...and also the error variable sice it's that loop that updates the E_n values
Zach Harrison
Zach Harrison 2021년 4월 16일
Thank you, that worked

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

추가 답변 (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