Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

for-loop

matlab

I have a for loop written in C:

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

How can I convert it to MATLAB?

like image 767
suter Avatar asked Dec 12 '11 11:12

suter


People also ask

How do you increment a for loop?

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.

What is the default increment value in a for loop in MATLAB?

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.

How do you give a loop in two increment?

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);


1 Answers

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.

like image 69
Chris Avatar answered Sep 24 '22 04:09

Chris