Alfonso Santiago
Alfonso Santiago

Reputation: 531

Defined Type with unspecified dimension Array in Julia

I'm Brand new in Julia. I've been looking around some documentation like [1], [2], [3]. Generally, I found it usefull, but I see some lack of organization in them. They all have the approach of "learning by examples" but any of them have a structured way to approach the remarkable features of the language.

Well, my problem is that I'm trying to build a defined type with some variables. Among them, at least one variable is an n-dimensional array where the dimensions are variables inside that defined type. To start, I cannot even define a fixed dimension tensor in the "struct".

Type Geometry
     dimension::UInt
     coordinates::Array{Float64}(10,2)
end

Says that:

expected Type, got Array.

and, for example:

Type Geometry
     dimension::UInt
     coordinates=Array{Float64}(10,2)
end

Says that:

"assignation" in Type definition is reserved.

Another approach would be define a "pointer" in the Type and then reshape that pointer, something like:

Type Geometry
     dimension::UInt
     coordinates::Float64
end

mesh=Geometry(10,0)
reshape(mesh.coordinates,(10,3))

Says that you cannot reshape an scalar.

So, my two questions are:

There's any way to build this dynamic dimension defined type in julia?

And even more important: do you have any recommended, organized and structured bibliography for julia like we've Metcalf. Fortran 95/2003 explained for fortran?

Thank you all.

Upvotes: 2

Views: 1010

Answers (1)

mbauman
mbauman

Reputation: 31342

You're looking at a very old version of Julia's documentation. Here is the documentation for the current stable version (0.6 right now).

The expression Array{Float64}(10,2) constructs a 10x2 array (a value). You define fields with types, not values. The corresponding type is Array{Float64, 2} — 2 for two dimensions. The exact number of elements isn't encoded into the array's type; that is part of the value. So you want:

type Geometry
     coordinates::Array{Float64, 2}
end

Of course, this means that every Geometry object must only contain a two-dimensional array. You can make it "dynamic" by simply omitting the parameter for the number of dimensions in the array type (but the tradeoff is that this won't perform as well):

type Geometry
     coordinates::Array{Float64}
end

Now you can construct Geometry objects with coordinate arrays of any dimensionality. A bit more advanced would be to use a parametric type, but I recommend getting the basics of the language down first.

Finally, note that reshape isn't an in-place operation. The returned array shares the data, but the first array retains its original shape.

Upvotes: 5

Related Questions