避免在MATLAB中嵌套for循环 [英] avoiding nested for loops in MATLAB
问题描述
我在MATLAB中有一种情况,我想为某些参数值评估函数.从任意数量的数组中提取参数,并且每个数组可以具有任意数量的元素.在调用函数之前,我知道数组的数量和其中的元素数量.
I have a scenario in MATLAB where I would like to evaluate a function for certain parameter values. The parameters are extracted from an arbitrary number of arrays, and each array can have an arbitrary number of elements. I know the number of arrays and the number of elements in them before I call the function.
例如,假设我有数组A = [a1 a2 ... aL]
,B = [b1 b2 ... bM]
和C = [c1 c2 ... cN]
.
For example, say I have arrays A = [a1 a2 ... aL]
, B = [b1 b2 ... bM]
and C = [c1 c2 ... cN]
.
for i = 1:length(A)
for j = 1:length(B)
for k = 1:length(C)
myfunc(A(i), B(j), C(k))
end
end
end
我正在考虑采用A
的L
元素,B
的M
元素和C
的N
元素,并将它们展平为单元格数组,并使用单个for循环进行迭代在这个细胞阵列上.
I am considering taking the L
elements of A
, M
elements of B
and N
elements of C
, and flatenning them into a cell array, and iterating with a single for loop over this cell array.
我想知道是否有一个MATLAB函数可以执行以下操作……结果不必一定是单元格数组.我想要一种避免多个嵌套的for循环的方法.少数循环是可以的,但是随着循环次数的增加,读取和维护它非常困难.
I was wondering if there was a MATLAB function that does something like this ... The result does not have to be a cell array. I want a way to avoid having multiple nested for loops. It is fine for a small number of loops, but as this number grows, it is pretty difficult to read and maintain.
推荐答案
aa
,bb
,cc
),因此可以使用单个索引(下面的k
)遍历所有组合.但是请注意,生成所有组合可能需要大量内存,具体取决于您的L
,M
,N
.
ndgrid
can be used to flatten several nested loops into one. It generates all combinations of values (variables aa
, bb
, cc
in the code below), so that a single index (k
below) can be used to traverse all combinations. But note that generating all combinations may required a lot of memory, depending on your L
, M
, N
.
[cc, bb, aa] = ndgrid(C, B, A); %// outermost variable should be rightmost here
for k = 1:numel(aa)
myfunc(aa(k), bb(k), cc(k));
end
这篇关于避免在MATLAB中嵌套for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!