It has nothing to do with whether you're using a Matrix (which is just an
Array{T,2}) or general Arrays. The question is, do you have to use
AbstractFloat?
julia> a = Float64[1,2,3]
3-element Array{Float64,1}:
1.0
2.0
3.0
julia> b = AbstractFloat[1,2,3]
3-element Array{AbstractFloat,1}:
1.0
2.0
3.0
julia> log(a.^2)
3-element Array{Float64,1}:
0.0
1.38629
2.19722
julia> log(b.^2)
ERROR: MethodError: `log` has no method matching log(::Array{Any,1})
julia> typeof(a.^2)
Array{Float64,1}
julia> typeof(b.^2)
Array{Any,1}
julia> Base.return_types(*, (AbstractFloat, AbstractFloat))
8-element Array{Any,1}:
Float32
Float64
Float16
BigFloat
BigFloat
BigFloat
Union{}
Any
You could do this:
julia> b2 = AbstractFloat[v^2 for v in b]
3-element Array{AbstractFloat,1}:
1.0
4.0
9.0
julia> log(b2)
3-element Array{Any,1}:
0.0
1.38629
2.19722
But overall, I highly recommend reading the performance tips page and these
two sections of the FAQ:
http://docs.julialang.org/en/stable/manual/faq/#what-does-type-stable-mean
http://docs.julialang.org/en/stable/manual/faq/#how-do-abstract-or-ambiguous-fields-in-types-interact-with-the-compiler
Best,
--Tim
On Monday, January 04, 2016 01:47:44 PM Charles Novaes de Santana wrote:
> Hi people,
>
> I would like to work with matrices represented as Arrays of Arrays of
> AbstractFloats. Something like this:
>
> F=Array{AbstractFloat}[];#initialize the matrix F as an Array of
> Arrays of Float
> for (i in 1:10)
> Fi = Array(AbstractFloat,0);#initialize the vector Fi as an
> Array of Float
> for (k in 1:5)
> push!(Fi,k^2+i^2)
> end#end-fork
> push!(F,Fi);
> end#end-fori
>
> typeof(F)
> Array{Array{AbstractFloat,N},1}
>
> But I am experiencing problems to work with rows/columns of such Arrays. I
> would like to calculate the logarithm of the square of elements of those
> rows/columns like this:
>
> f = F[1];#a vector of AbstractFloat
>
> typeof(f)
> Array{AbstractFloat,1}
>
> typeof(f.^2)
> Array{Any,1}
>
> log(f.^2)
> ERROR: MethodError: `log` has no method matching log(::Array{Any,1})
>
>
> I understand this error only happens because I am working with Arrays of
> Arrays of AbstractFloats. If I run a similar code using a Matrix instead of
> Array I don't have such problems:
>
> A = rand(10,5);#a matrix of floats (similar to an array of arrays)
>
> typeof(A)
> Array{Float64,2}
>
> a = A[1,:];#a vector of Float
>
> typeof(a)
> Array{Float64,2}
>
> typeof(a.^2)
> Array{Float64,2}
>
> log(a.^2)
>
>
> everything runs smoothly.
>
> My question: Am I doing something wrong in the way I am dealing with the
> Array of Arrays of AbstractFloat? Should I convert it to a Matrix? Or
> should I convert its elements to Array of Float instead of Array of Any?
> Any other suggestion?
>
> Thanks for your attention and for any advice!
>
> Charles