Home > Back-end >  Grid of all elements of an arbitrarily sized matrix in Julia
Grid of all elements of an arbitrarily sized matrix in Julia

Time:10-21

I have an n*m sized array A, and I would like to create a grid of its elements. The output should look something like:

B = (A[1,1], A[2,1]
     A[1,1], A[2,2]
     ...
     A[1,1], A[2,m]
     A[1,2], A[2,1]
     A[1,2], A[2,2]
     ...
     A[1,2], A[2,m]
     ...
     A[n,1], A[n,m])

My first approach would be to do something like this:

A = [1 5;
     2 6;
     3 7;
     4 8]

B = collect(Iterators.product(A))

However, this only returns

4×2 Matrix{Tuple{Int64}}:
 (1,)  (5,)
 (2,)  (6,)
 (3,)  (7,)
 (4,)  (8,)

Instead of the desired output above.

Any ideas?

CodePudding user response:

It was already answered by @DNF here:

https://discourse.julialang.org/t/grid-of-all-elements-of-an-arbitrarily-sized-matrix/89024/3

CodePudding user response:

Noone on the discourse.julialang.org link suggested:

hcat(repeat(A[:,1], inner=size(A,1)),repeat(A[:,2], outer=size(A,1)))

giving:

16×2 Matrix{Int64}:
 1  5
 1  6
 1  7
 1  8
 2  5
 2  6
 2  7
 2  8
 3  5
 3  6
 3  7
 3  8
 4  5
 4  6
 4  7
 4  8
  • Related