Parallel for loop over 2 variables

Is it possible in Octave to do 2 loops at the same time, for example:

(for i=0:10 && j=10:20)
  i;
  j;
  end

      

+3


source to share


3 answers


If the loops are the same length, then yes. It is not known that for non-vectors the for loop loops over columns. So just put your vectors in a matrix, one line per variable:

for r = [0:10; 10:20]
  printf ("1st is %2i; 2nd is %2i\n", r(1), r(2));
endfor

      



which returns:

1st is  0; 2nd is 10
1st is  1; 2nd is 11
1st is  2; 2nd is 12
1st is  3; 2nd is 13
1st is  4; 2nd is 14
1st is  5; 2nd is 15
1st is  6; 2nd is 16
1st is  7; 2nd is 17
1st is  8; 2nd is 18
1st is  9; 2nd is 19
1st is 10; 2nd is 20

      

+4


source


In Matlab, you can use arrayfun

with two input arrays of the same size:



>> arrayfun(@(x,y) x+y, 1:10, 10:10:100)
ans =
    11    22    33    44    55    66    77    88    99   110

      

+2


source


If you want them to move in a step, use a counter variable to refer to them as arrays:

j = 0:10;
i = 0:10;
for k = 1:11
    i(k);
    j(k);
end

      

But you most likely need to nest for loops:

for i = 0:10
    for j = 0:10
        i;
        j;
    end
end

      

+1


source







All Articles