Tutorial: for loop in C vs Matlab
There can be some confusion in translating a code from Matlab to C.
The most common mistake is in the for-loop syntax and index number.
Part 1. Iteration Counting
Iterate the loop 3 times
Total number of iteration : N
// MATLAB
for k=1:N fprintf ("hi"); end
// C-Prog: Option 1
for (k=0; k<N; k++) printf ("hi");
// C-Prog: Option 2
for (k=1; k<=N; k++) printf ("hi");
Find the 2^4 = 16 (x=2, N=4)
Part 2. Array Index
Use the array from the kth element, a total of N elements.
MATLAB: for k = kst : kend
Total number of array : N
Index End: kend= (N-1) + Kst
C-Prog: for (k = k0; k < Nmax; k++)
Total number of array : N
Index End: kend= (N-1) + Kst
Problem 1: Use the array from the 1st element, a total of N=7 elements. (e.g. 10 to 70)
MATLAB:
Total number of array : N=7
Index End: kend=7 // (7-1) + 1
C-Program:
Total number of array : N=7
Problem 2: Use the array from the 3rd element, a total of 4 elements. (e.g. 30,40,50,60)
MATLAB:
Total number of array : N=4
Index End: kend=6 // (4-1) + 3
C-Program:
Total number of array : N=4