In C++/C, we have multiple loop variables in a single loop, like for(int i=0; int j=0; i<5; j<5; i++; j++) Is there any facility in Matlab
MATLAB sort of supports multiple loop variables in that it supports a matrix as the loop expression. How does that work? Individual columns of the matrix are assigned to the loop variable at the beginning of each iteration.
Example code:
V = [1:1:5; 2:2:10]
for iv = V,
fprintf('iv = [%d %d];\n',iv);
end
Output:
V =
1 2 3 4 5
2 4 6 8 10
iv = [1 2];
iv = [2 4];
iv = [3 6];
iv = [4 8];
iv = [5 10];
We've achieved two loop variables here, iv(1) and iv(2), which are specified by the rows of the matrix used as the loop expression. Note that the array can be any type (e.g. string, cell, struct, etc.).
Summary
Pre-define each iteration of the loop variables, and store them as the rows of the matrix. Inside the loop, the loop variable will contain a column of the matrix.
Side note
I'm guessing that this convention is a consequence of the fact that the colon operator produces an array by horizontal concatenation rather than vertical. Just consider what happens in the following case:
for ii = (1:3).', numel(ii), end
You might be expecting three iterations, each indicating numel(ii)=1, but you only get one iteration and the loop reports:
ans =
3
The problem is clear if you are expecting ii to be a scalar.
Terminology
for loop_variable = loop_expression, statement, ..., statement end