Update: i and j values are 8 and 5 respectively and the end of the code so I guess that part works fine
Code not working, something with while loop
1 view (last 30 days)
Show older comments
Zach Harrison
on 16 Apr 2021
Commented: Zach Harrison
on 16 Apr 2021
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)
Accepted Answer
David Fletcher
on 16 Apr 2021
Edited: David Fletcher
on 16 Apr 2021
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 Comments
David Fletcher
on 16 Apr 2021
...and also the error variable sice it's that loop that updates the E_n values
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!