Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing matrix with a function

I'm looking for something in Julia like a comprehension but for a matrix instead of a vector. If i have some single-variable function f(x) and I want an array that is filled with f(i) for i in 1..10, I can do this:

[f(i) for i = 1:10]

If I have some two-variable function g(i,j) and I want a matrix from i=[1,10]; j=[1,10] filled with the function I can do this:

M = zeros (10,10)

for i in 1:10
     for j in 1:10
         M[i,j] = g(i,j)
     end
end

Is there some shortcut that allows me to express that in a shorter way and without wasting time allocating all that zeros?

like image 773
RedPointyJackson Avatar asked Feb 10 '23 09:02

RedPointyJackson


1 Answers

Just use a multidimensional comprehension directly:

julia> g(x,y) = 2x+y
g (generic function with 1 method)

julia> [g(i,j) for i=1:10, j=1:10]
10x10 Array{Int64,2}:
  3   4   5   6   7   8   9  10  11  12
  5   6   7   8   9  10  11  12  13  14
  7   8   9  10  11  12  13  14  15  16
  9  10  11  12  13  14  15  16  17  18
 11  12  13  14  15  16  17  18  19  20
 13  14  15  16  17  18  19  20  21  22
 15  16  17  18  19  20  21  22  23  24
 17  18  19  20  21  22  23  24  25  26
 19  20  21  22  23  24  25  26  27  28
 21  22  23  24  25  26  27  28  29  30

This works for any number of dimensions, by adding variable ranges at the end.

like image 83
mbauman Avatar answered Feb 11 '23 22:02

mbauman