Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an empty 2-dimensional array in Julia?

Tags:

m = [] 

initializes an empty array of dimension 1. I want to initialize an empty array of dimension 2 (to which I'll append values later on. Is this possible?

like image 850
becko Avatar asked Feb 01 '16 08:02

becko


People also ask

How do you initialize an empty array in Julia?

To initialize an empty array, it is perfectly valid to use n = 0 in the above expressions. A possible source of errors would be to confuse this array with an empty array of “Any” type, which is initialized as follows: v = [] # Same as Any[], and you can't change this type easily later (gotcha!)

How do you declare an array in Julia?

A 1D array can be created by simply writing array elements within square brackets separated by commas(, ) or semicolon(;). A 2D array can be created by writing a set of elements without commas and then separating that set with another set of values by a semicolon.

Are 2D arrays initialized 0?

Using Designated Initializers Its usage is demonstrated below, where the code explicitly initializes the first element of the array, and the remaining elements are automatically initialized with 0. That's all about initializing a 2D array with zeroes in C.

How do you create a matrix in Julia?

Julia provides a very simple notation to create matrices. A matrix can be created using the following notation: A = [1 2 3; 4 5 6]. Spaces separate entries in a row and semicolons separate rows. We can also get the size of a matrix using size(A).


Video Answer


2 Answers

As of Julia 1.0 you can use:

m = Array{Float64}(undef, 0, 0) 

for an (0,0)-size 2-D Matrix storing Float64 values and more in general:

m = Array{T}(undef, a, b, ...,z) 

for an (a,b,...,z)-size multidimensional Matrix (whose content is garbage of type T).

like image 186
Antonello Avatar answered Sep 24 '22 15:09

Antonello


Try:

m = reshape([],0,2) 

or,

m = Array{Float64}(undef, 0, 2) 

The second option which explicitly defines type should generate faster code.

A commenter ephemerally suggested using Matrix() for a 0x0 matrix and Matrix(0,2) for a 0x2 matrix.

like image 35
Dan Getz Avatar answered Sep 23 '22 15:09

Dan Getz