syntax error using complex loops

1 次查看(过去 30 天)
I have typed the following code and its saying invalid use of operator at line 10 which is the conditional statement for the for loop. It should be less than or equal to 19.
a=0;
b=input('Enter value of b');
count_outer=0;
total_iterations=0;
sum_ab=a+b;
while sum_ab <10000
counter_outer=counter_outer+1;
a=a+1;
c=3;
for c <= 19
c=3*c;
a=2*a+c;
b=10*c;
sum_ab=a+b;
total_iterations=total_iterations+1;
end end
disp(count_outer)
disp(total_iterations)
disp(sum_ab)

回答(2 个)

James Tursa
James Tursa 2020-10-4
Did you mean
while c <= 19
For loops should be looping over a fixed number of iterations, not a logical condition. While loops iterate over a logical condition like you have written.

Walter Roberson
Walter Roberson 2020-10-4
There are two loop structures in MATLAB: while and for
while is followed on the same line with a expression (most often a condition.) while tests to see that the expression is all non-zero, and if so then it executes the body of the loop. Then it loops back and tests the value of the expression again (using any updated versions of the variables that might have been changed), executes the body of the loop if the expression is all non-zero, and so on. Eventually at some point the condition is false or else the code does a break and the loop is executed. while is mostly used when there are an unknown known of repetitions to do.
for is followed by something that looks like an assignment to a simple (unindexed) variable. The right hand side of the assignment is examined and evaluated and the results of the evaluation are copied into internal variables. Then it loops setting the value of the variable to each of the columns of the saved value in turn. The list of values (and so the number of them) is determined at the time the for loop starts, so the for is mostly used when there are a known number of repetitions to do. Because the values of the expression in the loop header are recorded (in internal variables) at the beginning, changes to the variables involved do not have any effect on the for loop.
for K = 1 : 5
K = 6;
end
does not stop early. This is different than the C for loop:
for (K=1; K <= 5; K++) {K = 6;} // WOULD stop early
Now look at what you coded:
for c <= 19
The for is not followed by something that looks like an assignment.
It does not appear that the number of repetitions is known ahead of time, so you should probably be using a while

类别

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