问题
Say I have a for loop that counts from 10 down to 1 with counter k
. In the loop, when k
becomes 5, I make k=4
. When I output k
in each loop, I expected it would skip the 4 like so:
10 9 8 7 6 5 3 2 1
Instead I got all the numbers from 10 down to 1, it did not skip the 4. How can I make it so that it skips 4?
for k=10:-1:1
if i==5
k=i-1;
end
end
回答1:
You cannot modify the loop index from within the loop in MATLAB. Your two options are to omit that that index value prior to the loop
numbers = 10:-1:1;
numbers(numbers == 4) = [];
for k = numbers
% Stuff
end
Or you can use a while
loop rather than a for
loop
k = 10;
while k > 0
if k == 5
k = k - 1;
end
k = k - 1;
end
Or you can also do what @beaker has suggested with continue
.
回答2:
Modifying the loop variable is not really changing the loop. What you're changing is the value of the variable for that iteration. Instead, you can tell MATLAB to skip to the next iteration using continue:
for k=10:-1:1
if k==4
continue
end
disp(k)
end
Result:
10
9
8
7
6
5
3 <-- skipped 4
2
1
Edit: I just realized that you wanted to skip 4 and not 5. Code has been updated appropriately.
回答3:
If I remember correctly, Matlab creates an array when you call a for loop. If you enter
i = 10:-1:1
You end up with
i =
10 9 8 7 6 5 4 3 2 1
I'd recommend doing something like this:
for i = [10:-1:6, 4:-1:1]
i
<do some other stuff here>
end
this gets us from 10 down to 1 skipping 5.
回答4:
Here is an alternative method
NumbertoSkip = [4];
for k=10:-1:1
if(~ismember(NumbertoSkip,k))
disp(k)
end
end
The code checks if it the current k is present is not present in the NumbertoSkip
vector it displays it
You can skip any number just put it in the NumbertoSkip
Vector for example if NumbertoSkip = [4 5];
% 10
%
% 9
%
% 8
%
% 7
%
% 6
%
% 3
%
% 2
%
% 1
来源:https://stackoverflow.com/questions/37892123/how-to-update-counter-variable-in-a-for-loop