For loop not terminating when condition is met

1 view (last 30 days)
I have a for loop that counts up by 1 to a number. This number on each iteration is plugged into a matrix and a column vector of answers is outputted:
% constants:
R1 = 3000 ;
R2 = 8000 ;
R4 = 2000 ;
R5 = 4000 ;
% R3 = 2130 ; <--- this should be the answer for "r" below
v = 110 ;
for r = 2000:3000
R3 = r;
A = [0 -R2 0 -R4 0 0 % the "A" matrix
R1 -R2 R3 0 0 0
0 0 -R3 -R4 R5 0
-1 -1 0 0 0 1
0 1 1 -1 0 0
1 0 -1 0 -1 0
0 0 0 1 1 -1];
b = [-v; 0; 0; 0; 0; 0; 0];
x = A\b ; % the answer column vector
if x(4) == 0.0170
answer = r
break
end
end
In this code, "x" is a column vector. I want to terminate the for-loop when the "r" index causes the fourth row in x to be equal to 0.0170.
I know that the index value should be 2130, (in other words, I already know the answer) but the code doesn't "break" when this condition is met. Instead,
the for-loop keeps counting to whichever bound I told it to end at (in this case, 3000).
I'm sure I'm missing something simple here but I can't find what it is. Any help would be greatly appreciated!

Accepted Answer

Rik
Rik on 24 Mar 2019
Since Matlab stores values in a non-decimal representation, there is a lot of potential for round. In general you should be using a tolerance if you want to test equality for a non-integer data type. The required tolerance is an not really arbitrary choice, but depends on the context. If you expect an exact solution you should use something like 2*eps, while if you expect a non-exact solution you should use something that makes sense for you.
To get the exact answer you expected (2130), the precision needs to be a bit of an odd value. Also, a while loop makes more sense if you don't know how many iterations you need.
% constants:
R1 = 3000 ;
R2 = 8000 ;
R4 = 2000 ;
R5 = 4000 ;
% R3 = 2130 ; <--- this should be the answer for "r" below
v = 110 ;
solution_list=NaN(1,1000);%review the result for debugging
for r = 2000:3000
R3 = r;
A = [0 -R2 0 -R4 0 0 % the "A" matrix
R1 -R2 R3 0 0 0
0 0 -R3 -R4 R5 0
-1 -1 0 0 0 1
0 1 1 -1 0 0
1 0 -1 0 -1 0
0 0 0 1 1 -1];
b = [-v; 0; 0; 0; 0; 0; 0];
x = A\b ; % the answer column vector
solution_list(r-1999)=x(4);
if abs(x(4)-0.0170)<3.68*10^-6
answer = r
break
end
end

More Answers (0)

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!