I have a for
loop written in C:
for (int i = 0; i < 1000; i+=25)
How can I convert it to MATLAB?
A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.
d) 0/1. Explanation: When we are going to start a for loop in MATLAB, it is not necessary to assign a specific increment value. The default increment value will then be taken as 1.
A common idiom is to use the comma operator which evaluates both operands, and returns the second operand. Thus: for(int i = 0; i != 5; ++i,++j) do_something(i,j);
The MATLAB for loop syntax is
for i = values
program statements
:
end
where values
is one of
start:end
start:step:end
, orThe 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With