并发for循环超过2个变量

时间:2015-07-08 12:12:37

标签: matlab for-loop octave

Octave可以在同一时间制作2个循环,如:

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

3 个答案:

答案 0 :(得分:4)

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

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

返回:

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

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

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