我有一个N x 1的数组a,并且想要得到结果矩阵,其中元素是对a(I)&A(j)(i,j=1,…,N)。结果矩阵将看起来像[f(A(i),A(j))]。有人建议在不使用循环的情况下实现这一点吗?同样最好避免bsxfun,因为bsxfun在某些程序中没有实现。TKS
使用meshgrid
和arrayfun
:
[ii jj ] = ndgrid(1:N, 1:N); %// generate all combinations of i and j
result = arrayfun(@(n) f(A(ii(n)), A(jj(n))), 1:N^2);
result = reshape(result, length(A)*[1 1]); %// reshape into a matrix
示例:
N = 3;
A = [4 5 2];
f = @(x,y) max(x,y);
>>[ii jj ] = ndgrid(1:N, 1:N);
result = arrayfun(@(n) f(A(ii(n)), A(jj(n))), 1:N^2);
result = reshape(result, length(A)*[1 1])
result =
4 5 4
5 5 5
4 5 2
如果您不想要循环并且没有bsxfun
,则只剩下repmat
ra = repmat( A, [1 size(N,1)] );
res = f( ra, ra' ); % assuming f can be vectorized over matrices