问题
Q- Create a "counter" from 0:limit-1 (for example if you choose 3 it will display 0,1,2). The length of counter is not determined in the program and it should be determined when it is being run and the inputs can differ from each other
this is the solution on python but i want to compute it on matlab. how do i do that?
for i in range(3):
print(3-i)
for s in range(3,-1,-1)
print s
so the answer is :
3
2
1
3
2
1
0
回答1:
As Dan hinted you in the comments above, the colon operator of Matlab already do what you want.
Here are examples corresponding to your Python example:
Using the bare colon operator:
3:-1:0
gives
ans =
3 2 1 0
which is a 1 by 4 row vector.
You'll get the same result with:
limit = 3;
limit:-1:0
If you want to use this as a basis for a loop:
limit = 3;
for i = limit:-1:0
disp(i)
end
will output:
3
2
1
0
More generally you could do:
istart = 6;
istep = -2;
iend = 0;
for i = istart:istep:iend
disp(i)
end
which gives:
6
4
2
0
来源:https://stackoverflow.com/questions/16477439/create-a-counter-on-matlab-from-0limit-1-the-length-of-counter-is-not-determ