2

Say I have a simple function with three inputs

f = @(a,b,c) a+b+c

I would like to evaluate this function on combinations of inputs

A = 1:10
B = 2:2:10
C = 0.1:0.1:1

and store the output in a matrix F.

Right now I am doing this as follows:

F = NaN(length(A),length(B),length(C));

for ia = 1:length(A)
   for ib = 1:length(B)
     for ic = 1:length(C)
        F(ia,ib,ic) = f(A(ia),B(ib),C(ic))
     end
   end
end

I am wondering if there is an efficient way to do this without the use of sloppy for loops, *and without having to vectorize the function f.

Berk U.
  • 7,018
  • 6
  • 44
  • 69

1 Answers1

4

If you want neat syntax and don't care much about memory or speed, you can use:

  1. ndgrid to generate all combinations; and then
  2. arrayfun to call f on each combination:

The second step exploits the fact that arrayfun can be called with several arrays as input, and in that case it takes corresponding elements from each array:

[aa, bb, cc] = ndgrid(A,B,C);        %// step 1
result = arrayfun(f, aa, bb, cc);    %// step 2

As for the memory and speed concerns I mentioned above:

  • Step 1 requires quite a lot of memory if the input vectors are large, because all combinations are generated at once.
  • Step 2 may result in code slower than using for loops; see for example here.
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147