Defining a array type

Newbie question, but how can I define an array type (like Java or C)?

I know is posible to do in local variables like:

function f(X::Int64)
    Y::Int64 = 0
end

How to define an array type?

Thanks!

I’m not sure that an Array type is the answer for you.
If it is, nevermind … :slight_smile:

In general, arrays may have 1,2,…n dimensions. Most of the time, people are working with Vectors, Matricies or other small dimension arrays. To create an array, one easy way is to create it zero-filled:

julia> element_type = Int
julia> nzeros = 4
julia> myvector = zeros(element_type, nzeros)
4-element Vector{Int64}:
 0
 0
 0
 0

To create a matrix, do something similiar

julia> element_type = Float32
julia> nrows = 3
julia> ncols  = 4
julia> mymatrix = zeros(element_type, nrows, ncols)
3×4 Matrix{Float32}:
 0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0

Of course you do not need to use the variables.
mymatrix = zeros(Float32, 3, 4) does the same thing.

For 3D arrays, use 3 counts

julia> my3Darray = zeros(Int, 4, 3, 2)
4×3×2 Array{Int64,3}:
[:, :, 1] =
 0  0  0
 0  0  0
 0  0  0
 0  0  0

[:, :, 2] =
 0  0  0
 0  0  0
 0  0  0
 0  0  0
3 Likes

I don’t quite understand what you’re asking for. Could you write the Java/C code for which you want the equivalent Julia code?

3 Likes

In Java we can write:

int[] array = {1,2,3};

This means that this array only receive int values

1 Like
julia> array = Int[1, 2]
2-element Vector{Int64}:
 1
 2

julia> array = Int[1, 2.0]
2-element Vector{Int64}:
 1
 2

julia> array = Int[1.0, 2.0]
2-element Vector{Int64}:
 1
 2

julia> array[2] = 1.5
ERROR: InexactError: Int64(1.5)
2 Likes

v = [1, 2]

will automatically make an array of integers (without needing to explicitly specify the type).

4 Likes

Thanks for the complete answer!
I didn’t know that I could define the type in the first parameter!

Thanks a lot!

Especially if you’re just starting with the language, don’t use type annotations. You don’t need them.

8 Likes