Evaluate matrix expression at grid points with Julia
I had a small (possibly inefficient) Matlab code that generated a matrix of values โโof the product function of the grid points of the grid. For example:
N = 2 ; r = -N:N ; [X1, X2] = ndgrid( r, r ) ; f = @( x ) ( x ) ; % identity: dummy function for this example. X1 X2 f( X1 .* X2 )
production:
X1 =
-2 -2 -2 -2 -2
-1 -1 -1 -1 -1
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
X2 =
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
ans =
4 2 0 -2 -4
2 1 0 -1 -2
0 0 0 0 0
-2 -1 0 1 2
-4 -2 0 2 4
It was based on this answer and this Matlab Calculate function using gridded domain text.
I can implement this in Julia with a bunch of looping over a grid:
N = 2 ;
r = -N:N ;
twoNplusOne = 2*N + 1 ;
F = zeros( twoNplusOne, twoNplusOne ) ;
f = identity ; #say
for n = 1:twoNplusOne
for m = 1:twoNplusOne
F[ n, m ] = f( r[n]*r[m] ) ;
end
end
F
... but was wondering if there is a more natural (and efficient) way to do this in Julia?
source to share
Not sure if this is the canonical Julian approach, but you can use broadcast
:
julia> broadcast((x,y)->f(x*y), -N:N, (-N:N)')
5x5 Array{Int32,2}:
4 2 0 -2 -4
2 1 0 -1 -2
0 0 0 0 0
-2 -1 0 1 2
-4 -2 0 2 4
where i used '
to rotate a range from one dimension (5,)
to one of (1,5)
. In fact, in this particular case, since the function takes a scalar argument and only depends on the product of your X1 and X2, we could even get away with
julia> f((-N:N) .* (-N:N)')
5x5 Array{Int32,2}:
4 2 0 -2 -4
2 1 0 -1 -2
0 0 0 0 0
-2 -1 0 1 2
-4 -2 0 2 4
but this does not have to be true in general.
source to share