MATLAB - avoiding loops to create a matrix based on the elements of other vectors

matlab

Solution

x=[1 2 3 4];
y=[5 6];
z=[7 8 9];
[X Y Z]=meshgrid(x,y,z);
someFunc = @(a,b,c)[a b c]; #% test function; use whatever you want
Q = arrayfun(someFunc,X,Y,Z,'UniformOutput',false);
Q{1,1,1} #% output: [1 5 7]

If someFunction is defined elsewhere, use `arrayfun(@someFunction,X,Y,Z);` to get a handle to it. (`arrayfun` uses each element of the arguments as args to the function handle you provide - it, and the related cellfun, are key in avoiding loops.)

Problem

Suppose I have vectors `x,y,z`, of lengths `n,m,l`. I want to create a cell matrix `Q` using the elements of those vectors. Naively one could use a for loop as so: ``` for i = 1:n for j = 1:m for k = 1:l Q{i,j,k} = someFunction(x(i), y(j), z(k)); end end end ``` Each element of `Q` is a vector. Is there a more elegant (and probably less slow) way to do this?

Original source