2

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 for multiple variables loop? And also, I'm very conscious in loop iterations computations, so does it effects the speed as I'v already a nested loop in Matlab.

  • 2
    If both `i` and `j` follow the same start and end values, why not just use loop for `i` i.e. `for i=0:4` and then declare `j=i`? Also, I think the condition to continue with the loop has to be one and not mutiple ones - `i<5; j<5;`. – Divakar Apr 25 '14 at 17:46
  • 2
    Also, the commands need to be separated by a comma in C++. You have three sections, separated by two semicolons: `for(INITIALIZATION; CONDITION; INCREMENT) command;`. Your example could be like this: `for(int i=0, j=0; i<5 && j<5; i++, j++)` – Rafael Monteiro Apr 25 '14 at 17:49

3 Answers3

9

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
chappjc
  • 30,359
  • 6
  • 75
  • 132
  • @AhsanAli It's usually beneficial to look at MATLAB `for` loop expressions as temporary (constant) variables, to avoid problems like the one in [this question](http://stackoverflow.com/a/23136986/2778484) (linking to my answer since it's relevant to the point). – chappjc Apr 26 '14 at 00:37
  • 2
    Wow.. +1. I just noticed this. This is very akin to `zip` in Python when you have 2 lists of numbers. Really cool! – rayryeng Oct 17 '14 at 22:40
2

MATLAB doesn't have the capability of doing multiple loop variables, you will have to use nested for-loops. That said, one of MATLAB's greatest strengths is efficiently applying a function across an array.

For example:

a = zeros(1,5);
for i=1:5
    a(i) = sin(i);
end

b = sin(1:5);

In the above example a & b will be identical, but calculating b doesn't require an explicit for-loop. There are times when explicit for-loops (including nested loops) are necessary (like running a simulation via the sim command), but since you are concerned about the time to compute the loop iterations, my guess is you aren't running time-intensive tasks like a massive simulation.

So rather than using nested for-loops, I'd look into setting up your functions to work with arrays and input your "loop variables" as the arrays. Look into the commands meshgrid & griddata to help create those arrays.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Matt_D
  • 29
  • 2
0

As chappjc pointed out, and as MathWorks states in the documentation, each iteration of a for loop takes the next column of the iterator. Thus, to iterate through a column vector, for example, one must transpose it (i.e. for ii = [1; 1; 2; 3; 5]'), otherwise ii is equal to the column vector, all at once.

And merely to extend chappjc's excellent answer, you may take advantage of this behavior with cells, also, where you might have some differently sized strings, in addition to wanting a numeric iterator, and then you can deal them to variables so you don't have to do as much indexing. Here is a crude example:

figure(1)
imageList = {};
for ii = [{somePath; someDirListing; 1}, {anotherPath; anotherDirListing; 2}] % Each iteration takes one column

    [pathname, images, iPos] = deal(ii{:});

    for iImage = images
        img = imread(fullfile(pathname, iImage));
        imagesc(img)
        axis image
        if iPos == 1
            title(['This is a left image, titled ' iImage])
        else
            title(['This is a right image, titled ' iImage])
        end
        pause(1)
    end
end
benJephunneh
  • 658
  • 10
  • 14