Pregunta

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

¿Fue útil?

Solución

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

Otros consejos

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top