How to work on a specific field of an vector of structure?

I have the below R instance of Rs structure. I want to work on a specific field of all rows (as dealing with Matrix). So, I am using R[:].I[:] but it gives an error. Any way to do that?

Base.@kwdef mutable struct Rs
    I::Vector{Float64} = [2,2,2]
    Dot::Array{Float64, 2} = [0 0 0; 0 0 0; 0 0 0]
R = Rs[];
push!(R, Rs());
push!(R, Rs());

julia> R[:].I[:]
ERROR: type Array has no field I
 [1] getproperty(x::Vector{Rs}, f::Symbol)
   @ Base .\Base.jl:33
 [2] top-level scope
   @ REPL[1]:1

R is a vector, and doesn’t have a field, I. You can do R[i].I to access the field of the ith element of R. To get a vector of all the Is, you can try

getproperty.(R, :I) 

R[:] doesn’t do anything useful, it just returns a vector of all the elements of R, so it’s equal to R itself.

@DNF thank you very much. Using getproperty.(R, :I), return 2-elemnt Vector of vector, as below:

julia> getproperty.(R, :I)
2-element Vector{Vector{Float64}}:
 [2.0, 2.0, 2.0]
 [2.0, 2.0, 2.0]

Can I do something to return this results as Array{2, Float64}, i.e.

2×3 Matrix{Float64}:
 2.0  2.0  2.0 # as R[1].I
 2.0  2.0  2.0 # as R[2].I

You’ll have to explicitly combine them. You should not put them along rows, though, but columns.


reduce(hcat, getproperty(r, :I) for r in R) 


1 Like


Thank you very much, but it gives the results transposed

julia> reduce(hcat, getproperty(r, :I) for r in R)
3×2 Matrix{Float64}:
 2.0  2.0
 2.0  2.0
 2.0  2.0

Yes, as I said, this is the correct orientation. Julia Arrays are column major, so things should be laid out in column order.

1 Like

Ok, thank you very much!