将函数应用于MATLAB中两个矩阵中的每一对列 [英] Apply function to every pair of columns in two matrices in MATLAB
问题描述
在MATLAB中,我想将一个函数应用于矩阵A
和B
中的每对列向量.我知道必须有一种有效的方法(非for
),但是我无法弄清楚.该函数将输出一个标量.
In MATLAB, I'd like to apply a function to every pair of column vectors in matrices A
and B
. I know there must be an efficient (non for
) way of doing this, but I can't figure it out. The function will output a scalar.
推荐答案
尝试
na = size(A,1);
nb = size(B,1);
newvector = bsxfun(@(j,k)(func(A(j,:),B(k,:))),1:na,(1:nb)');
bsxfun
在1:na和(1:nb)'上执行单例扩展.在这种情况下,最终结果是将func应用于从A和B提取的每对列向量.
bsxfun
performs singleton expansion on 1:na and (1:nb)'. The end result, in this case, is that func will be applied to every pair of column vectors drawn from A and B.
请注意,bsxfun可能很棘手:它可能要求所应用的函数本身支持单例扩展.在这种情况下,它将可以完成您想要的工作.
Note that bsxfun can be tricky: it can require that the applied function support singleton expansion itself. In this case it will work to do the job you want.
这篇关于将函数应用于MATLAB中两个矩阵中的每一对列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!