pairwise evlaluation without using loop

79 views Asked by At

I have a N x 1 array A, and want to get the result matrix with elements being evaluation of function f (such as max) on pairs A(i) & A(j) (i, j =1,...,N). The result matrix will look like [ f(A(i), A(j))]. Any one have suggestions to achieve this without using loop? Also better avoid bsxfun, since bsxfun is not implemented in some program. TKS

2

There are 2 answers

0
Luis Mendo On BEST ANSWER

Use meshgrid and 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

Example:

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
0
Shai On

If you do not want loops and no bsxfun you are left with repmat

ra = repmat( A, [1 size(N,1)] );
res = f( ra, ra' ); % assuming f can be vectorized over matrices