0

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Neha Irfan
  • 1
  • 1
  • 4
  • http://www.mathworks.com/help/matlab/ref/colon.html Use the colon operator, see the first example in that link. This is one of the fundamental syntax elements of Matlab. – Dan May 10 '13 at 07:49
  • so youre saying that i should use the first example for my question? – Neha Irfan May 10 '13 at 08:06
  • what about the "print" command? – Neha Irfan May 10 '13 at 08:07
  • you don't need a print command in matlab, you can just leave off the ; at the end and it will print the result of that line to the command line. If you want to be a bit neater you can look at `disp` or also `sprintf` – Dan May 10 '13 at 08:16
  • can you please help me with the solution? – Neha Irfan May 10 '13 at 08:25
  • This is literally the most basic Matlab question you could possibly be asking. Do some tutorials. The solution is `0:(limit-1)`, that is literally the solution. – Dan May 10 '13 at 08:28

1 Answers1

2

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
Zertrin
  • 250
  • 3
  • 9