Conversion of a 'for' loop with an increment of 25 from C to MATLAB
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
suter
Updated on July 30, 2022Comments
-
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 over 12 yearsI think you mean
for i
, not justi
. And you don't need the[]
surrounding the colon expression. -
Chris over 12 years-1 This does not give the right answer:
for(int i = 0; i < 1000; i+=25)
yields the numbers0 25 50 ... 950 975
where asi = 0:25:1000
yields0 25 50 ... 950 975 1000
. Ifi < 1000;
were replaced withi <= 1000;
or ifi = 0:25:975
was used then the output would match. -
Dang Khoa over 12 yearsAlso note that
i=[0:25:1000]
actually means something different thani=0:25:1000
- in the first case, you are actually preallocating memory to store the vector0:25:1000
. This might not matter for this loop, but compare toi=1:inf
andi=[1:inf]
.