问题描述
我有一个函数f
,它使用2个具有相同行数的矩阵并求出一个标量值.现在,我正在寻找创建新函数的可能性,该函数需要两个矩阵列表并为所有对调用f
.
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
(不要求X和Y是单元格)
(It is not a requirement that X and Y are cells)
例如f
可以是距离平方的均值
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)));
但不要质疑f
,这只是一个更为复杂的问题的示例.
but don't question f
, it is just an example of a much more complicated problem.
推荐答案
首先,您应该预先分配M
.然后,您可以使用meshgrid
轻松生成一个循环,以生成X和Y中所有成对的元素的列表:
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
但是,如果可以实现f
以便对其进行正确的矢量化处理,则可以将其传递给两个3D矩阵,即X和Y对的整个列表,并且完全没有循环.但这完全取决于您的f
是做什么的.
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.
这篇关于评估所有成对的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!