'Julia: how to index an 'any' type array
I am new in Julia. I want to replicate the results in Wollmann (2019). However, it always give me this error: LoadError: MethodError: no method matching setindex!(::Type{Array{Any, 100}}, ::Matrix{Int64}, ::Int64).
Here is the code:
i=1
hArray = Array{Any,100}
tbx_temp = (tbx_t.==(1996-1985))+(tbx_t.==(2000-1985))+(tbx_t.==(2005-1985))
hArray[i]=tbx_temp.*tbx_enter.*(sum(tbx_x1[:,3:4],dims=2).==0) .* sum(tbx_h_x[:,2:4],dims=2); i=i+1;
#tbx_t is an Int64 vector, and looks like this:
13824-element Vector{Int64}: [1;1;1;...;27;27;27]
#tbx_enter is a bitvector, either 0 or 1.
#tbx_x1 is a float64 matrix:
13824×2 Matrix{Float64}:
[1.0 0.0; 0.0 1.0;...;0.0 0.0; 0.0 0.0]
#tbx_h_x is a bitmatrix, either 0 or 1 13824×3 BitMatrix:
[0 0 0; 0 1 0;...;1 0 1; 0 0 0]
Thanks in advance!
Solution 1:[1]
The line hArray = Array{Any,100}
simply describes the type of a 100-dimensional array. It does not construct a 100-element vector. To create such an array (without initializing its elements), use the Array constructor, or perhaps more clearly, the Vector constructor:
# Using Array constructor
hArray = Array{Any}(undef, 100)
#Using Vector constructor
hArray = Vector{Any}(undef, 100)
However, it is typically poor practice to use the Any
type without good reason. For example, performance can decrease when using abstract types. Your snippet indicates that the elements of hArray are likely Float64. If that is the case, you can use:
hArray = Vector{Float64}(undef, 100)
Even if you aren't sure exactly which data type is appropriate, using a smaller abstract type such as Number
or Real
is better practice than using Any
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mrouleau |