Conversion of a 'for' loop with an increment of 25 from C to MATLAB

17,191

Solution 1

The for loop

for (int i = 0; i <= 1000; i+=25)

can be converted to MATLAB for loop in this way:

>> for i = [0:25:1000]
   # Code
   end

Solution 2

The MATLAB for loop syntax is

for i = values
    program statements
      :
end

where values is one of

  • start:end
  • start:step:end, or
  • an array of values.

The form start:end assumes a step of 1, whereas you want a step (or increment) of 25, so use the second form. From your question, for(int i = 0; i < 1000; i+=25) generates a list of the numbers 0 25 50 ... 950 975, i.e. it does not include 1000 (notice the i < 1000; in the for loop), so we can't use end=1000 in out MATLAB syntax. Instead use end = 1000-25 = 975:

for i = 0:25:975
    program statements
      :
end

will yield the same values of i as the C equivalent.

Note: see my comment on Mithun Sasidharan's answer. His answer yields different numbers for the C and MATLAB for loops (and he seems to have dropped the for from his MATLAB answer). His answer gives 0 25 50 ... 950 975 for the C loop and 0 25 50 ... 950 975 1000 for his MATLAB code.

Edit: Aashish Thite's answer raises an important point about for loops and array indexing which differs between C and MATLAB.

Solution 3

If you are going to use 'i' as an index for scanning through an array, for i=0:25:1000 will not work. The index of the first element in an array of matlab is 1. So use for i=1:25:1000

Share:
17,191
suter
Author by

suter

Updated on July 30, 2022

Comments

  • suter
    suter almost 2 years

    I have a for loop written in C:

    for (int i = 0; i < 1000; i+=25)
    

    How can I convert it to MATLAB?

  • Sam Roberts
    Sam Roberts over 12 years
    I think you mean for i, not just i. And you don't need the [] surrounding the colon expression.
  • Chris
    Chris over 12 years
    -1 This does not give the right answer: for(int i = 0; i < 1000; i+=25) yields the numbers 0 25 50 ... 950 975 where as i = 0:25:1000 yields 0 25 50 ... 950 975 1000. If i < 1000; were replaced with i <= 1000; or if i = 0:25:975 was used then the output would match.
  • Dang Khoa
    Dang Khoa over 12 years
    Also note that i=[0:25:1000] actually means something different than i=0:25:1000 - in the first case, you are actually preallocating memory to store the vector 0:25:1000. This might not matter for this loop, but compare to i=1:inf and i=[1:inf].