Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tiling or repeating n-dimensional arrays in Julia

Tags:

matrix

julia

I am looking for a general function to tile or repeat matrices along an arbitrary number of dimensions an arbitrary number of times. Python and Matlab have these features in NumPy's tile and Matlab's repmat functions. Julia's repmat function only seems to support up to 2-dimensional arrays.

The function should look like repmatnd(a, (n1,n2,...,nk)). a is an array of arbitrary dimension. And the second argument is a tuple specifying the number of times the array is repeated for each dimension k.

Any idea how to tile a Julia array on greater than 2 dimensions? In Python I would use np.tile and in matlab repmat, but the repmat function in Julia only supports 2 dimensions.

For instance,

x = [1 2 3]
repmatnd(x, 3, 1, 3)

Would result in:

1 2 3
1 2 3
1 2 3

1 2 3
1 2 3
1 2 3

1 2 3
1 2 3
1 2 3

And for

x = [1 2 3; 1 2 3; 1 2 3]
repmatnd(x, (1, 1, 3))

would result in the same thing as before. I imagine the Julia developers will implement something like this in the standard library, but until then, it would be nice to have a fix.

like image 309
jtorca Avatar asked Jul 20 '14 02:07

jtorca


People also ask

How do you initialize an array in Julia?

An Array in Julia can be created with the use of a pre-defined keyword Array() or by simply writing array elements within square brackets([]). There are different ways of creating different types of arrays.

How do you flip the matrix in Julia?

Flipping a matrix: A matrix in Julia can be flipped via the X-axis i.e. horizontally or via the Y-axis i.e. vertically. To flip the matrix we use reverse(< matrix >, dims= < 1 or 2 >)) 1 = vertically, 2 = horizontally.

How do you fill an array in Julia?

Create an array filled with the value x . For example, fill(1.0, (10,10)) returns a 10x10 array of floats, with each element initialized to 1.0 . If x is an object reference, all elements will refer to the same object. fill(Foo(), dims) will return an array filled with the result of evaluating Foo() once.

How do you find the dimensions of a matrix in Julia?

The size() is an inbuilt function in julia which is used to return a tuple containing the dimensions of the specified array. This returned tuple format is (a, b, c) where a is the rows, b is the columns and c is the height of the array.


1 Answers

Use repeat:

julia> X = [1 2 3]
1x3 Array{Int64,2}:
 1  2  3

julia> repeat(X, outer = [3, 1, 3])
3x3x3 Array{Int64,3}:
[:, :, 1] =
 1  2  3
 1  2  3
 1  2  3

[:, :, 2] =
 1  2  3
 1  2  3
 1  2  3

[:, :, 3] =
 1  2  3
 1  2  3
 1  2  3
like image 168
John Myles White Avatar answered Sep 19 '22 10:09

John Myles White