可以在MATLAB中完成并行遍历,就像在Python中一样吗?

Jas*_*son 11 python arrays matlab for-loop

使用该zip函数,Python允许循环并行遍历多个序列.

for (x,y) in zip(List1, List2):

MATLAB有相同的语法吗?如果没有,使用MATLAB同时迭代两个并行数组的最佳方法是什么?

mat*_*ast 15

如果x和y是列向量,则可以执行以下操作:

for i=[x';y']
# do stuff with i(1) and i(2)
end
Run Code Online (Sandbox Code Playgroud)

(使用行向量,只需使用xy).

这是一个示例运行:

>> x=[1 ; 2; 3;]

x =

     1
     2
     3

>> y=[10 ; 20; 30;]

y =

    10
    20
    30

>> for i=[x';y']
disp(['size of i = ' num2str(size(i)) ', i(1) = ' num2str(i(1)) ', i(2) = ' num2str(i(2))])
end
size of i = 2  1, i(1) = 1, i(2) = 10
size of i = 2  1, i(1) = 2, i(2) = 20
size of i = 2  1, i(1) = 3, i(2) = 30
>> 
Run Code Online (Sandbox Code Playgroud)


sve*_*ven 6

如果我没弄错你在python中使用的zip函数会创建一对list1和list2中找到的项目.基本上它仍然是一个for循环添加它将从你的两个单独的列表中检索数据,而不是你必须自己做.

所以也许你最好的选择是使用这样的标准 for循环:

for i=1:length(a)
  c(i) = a(i) + b(i);
end
Run Code Online (Sandbox Code Playgroud)

或者与数据有关的任何事情.

如果你真的在谈论并行计算,那么你应该看看用于matlab 的并行计算工具箱,更具体地说是在parfor


DMC*_*DMC 6

仅在八度音阶中测试...(没有matlab许可证).存在arrayfun()的变体,请查看文档.

dostuff = @(my_ten, my_one) my_ten + my_one;

tens = [ 10 20 30 ];
ones = [ 1 2 3];

x = arrayfun(dostuff, tens, ones);

x
Run Code Online (Sandbox Code Playgroud)

产量...

x =

   11   22   33
Run Code Online (Sandbox Code Playgroud)