并发 for 循环 2 个变量

concurrent for loop over 2 variables

在 Octave 中是否可以同时进行 2 个循环,例如:

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

如果您希望它们同步移动,请使用计数器变量将它们作为数组引用:

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

但您很可能需要进行嵌套 for 循环:

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

如果循环长度相同,则可以。鲜为人知的是,对于非向量,for 循环在列上循环。因此,只需将向量放在矩阵中,每个变量一行:

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

哪个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

在 Matlab 中,您可以使用 arrayfun 和两个相同大小的输入数组:

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