Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the array of struct field value in Julia

Tags:

julia

Let's say I want to define the following object

mutable struct Coord
x::Float
y::Float
end

and create a vector of the coordinate

coordVec = Vector{Coord}(undef, 3)

by using for loop we can define the value of coordinate in the coordVec, but how to assign a new value of the coordinate? I have try following way but not working

coordVec[1].x = 3.1
(p->p.x).(coordVec)[1] = 3.1
like image 392
Lele Mabur Avatar asked Mar 03 '23 12:03

Lele Mabur


1 Answers

The problem is that your array coordVec is uninitialized because you used the undef to construct the array, meaning its values are undefined:

julia> coordVec = Vector{Coord}(undef, 3)
3-element Array{Coord,1}:
 #undef
 #undef
 #undef

And therefore you can't update the fields. If you put Coord objects in your array you can update them as expected:

julia> coordVec[2] = Coord(1, 2)
Coord(1.0, 2.0)

julia> coordVec[2].x = 3.0
3.0

julia> coordVec
3-element Array{Coord,1}:
 #undef
    Coord(3.0, 2.0)
 #undef
like image 126
Jakob Nissen Avatar answered Jun 05 '23 03:06

Jakob Nissen