Evaluate all pairs of matrices

Man*_*idt 0 matlab matrix

I have a function f which takes 2 matrices with the same number of rows and procudes a scalar value. A am now looking for a possibility to create a new function which takes two lists of matrices and calls f for all pairs.

I need a moore efficient implementation of this loop:

% X = cell of matrices
% Y = cell of matrices
for k=1:length(X)
    for l=1:length(Y)
        M(k,l) = f(X{k},Y{l});
    end
end
Run Code Online (Sandbox Code Playgroud)

(It is not a requirement that X and Y are cells)

For example f could be the mean of squared distances

f = @(X,Y) mean(mean(bsxfun(@plus,dot(X,X,1)',dot(Y,Y,1))-2*(X'*Y)));
Run Code Online (Sandbox Code Playgroud)

but don't question f, it is just an example of a much more complicated problem.

Dan*_*Dan 5

Firstly you should be pre-allocating M. Then you can cut out one loop quite easily by using meshgrid to generate a list of all pairs of elements in X and Y:

[K, L] = meshgrid(1:length(X), 1:length(Y));

M = zeros(size(K));  %//This preallocation alone should give you a significant speed up
for ii = 1:numel(K)
    M(ii) = f(X{K(ii)},Y{L(ii)});
end
Run Code Online (Sandbox Code Playgroud)

However, if you can implement f so that it is properly vectorized, you might be able to pass it two 3D matrices, i.e. the entire list of X and Y pairs and do it without a loop at all. But this depends entirely on what it is that your f does.