Question

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

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top