Create a “counter” on matlab from 0:limit-1. The length of counter is not determined in the program

你说的曾经没有我的故事 提交于 2019-12-11 20:39:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!