0

我有一个 N x 1 数组 A,并且想要获得结果矩阵,其中元素是对 A(i) & A(j) (i, j =1,..., N)。结果矩阵看起来像 [ f(A(i), A(j))]。有没有人建议在不使用循环的情况下实现这一目标?最好避免使用 bsxfun,因为某些程序中没有实现 bsxfun。TKS

4

2 回答 2

1

使用meshgridarrayfun

[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
于 2013-12-10T19:21:48.380 回答
0

如果你不想要循环并且没有bsxfun,你就剩下repmat

ra = repmat( A, [1 size(N,1)] );
res = f( ra, ra' ); % assuming f can be vectorized over matrices
于 2013-12-10T17:02:45.403 回答