问题
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.
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
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.
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.
回答1:
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
回答2:
Thanks to direction from the accepted answer, I made a function that generalizes to any number of arrays. The result is a 2D array of N-tuples - where N is the number of input arrays.
function [Result] = makeTuples(varargin)
nInputArgs = length(varargin);
b = cell(1, nInputArgs);
a = flip(varargin);
[b{:}] = ndgrid(a{:});
bb = flip(b);
nOutputs = length(bb);
N = numel(bb{1});
Result = zeros(N, nInputArgs);
arr = zeros(1,nInputArgs);
for j = 1:N
for k = 1:nOutputs
arr(k) = bb{k}(j);
end
Result(j,:) = arr;
arr = zeros(1,nInputArgs);
end
end
来源:https://stackoverflow.com/questions/27138616/avoiding-nested-for-loops-in-matlab