14

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

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

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

4

7 回答 7

19

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

for i=[x';y']
# do stuff with i(1) and i(2)
end

(使用行向量,只需使用xand y)。

这是一个示例运行:

>> 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
>> 
于 2008-09-15T19:20:15.590 回答
8

Tested only in octave... (no matlab license). Variations of arrayfun() exist, check the documentation.

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

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

x = arrayfun(dostuff, tens, ones);

x

Yields...

x =

   11   22   33
于 2008-09-09T02:32:46.670 回答
6

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

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

for i=1:length(a)
  c(i) = a(i) + b(i);
end

或者你必须对数据做的任何事情。

如果你真的在谈论并行计算,那么你应该看看Parallel Computing Toolbox for matlab,更具体地说是parfor

于 2008-09-08T11:34:08.047 回答
2

我建议加入两个数组进行计算:

% assuming you have column vectors a and b
x = [a b];

for i = 1:length(a)
    % do stuff with one row...
    x(i,:);
end

如果您的函数可以与向量一起使用,这将非常有用。再说一次,许多函数甚至可以使用矩阵,所以你甚至不需要循环。

于 2008-10-20T14:22:59.297 回答
0
for (x,y) in zip(List1, List2):

应该是例如:

>> for row = {'string' 10
>>           'property' 100 }'
>>    fprintf([row{1,:} '%d\n'], row{2, :});
>> end
string10
property100

这很棘手,因为单元格大于 2x2,并且单元格甚至是转置的。请试试这个。

这是另一个例子:

>> cStr = cell(1,10);cStr(:)={'string'};
>> cNum=cell(1,10);for cnt=1:10, cNum(cnt)={cnt};
>> for row = {cStr{:}; cNum{:}}
>>    fprintf([row{1,:} '%d\n'], row{2,:});
>> end
string1
string2
string3
string4
string5
string6
string7
string8
string9
string10
于 2019-02-01T15:52:49.630 回答
0

如果我有两个具有相同维度 No 2 大小的数组 al 和 bl 并且我想遍历这个维度(比如 multiply al(i)*bl(:,i))。那么下面的代码就可以了:

al = 1:9;
bl = [11:19; 21:29];

for data = [num2cell(al); num2cell(bl,1)]

    [a, b] = data{:};
    disp(a*b)

end
于 2020-10-16T13:13:00.047 回答
-2

forMATLAB 中的循环过去很慢,但现在不再如此。

所以矢量化并不总是奇迹般的解决方案。只需使用分析器tictoc函数来帮助您识别可能的瓶颈。

于 2008-09-26T11:31:27.207 回答