diff --git a/src/mxarray.jl b/src/mxarray.jl index e0f5b26..ae77272 100644 --- a/src/mxarray.jl +++ b/src/mxarray.jl @@ -264,7 +264,8 @@ function mxarray(a::Array{T}) where T<:MxRealNum return mx end -function mxarray(a::Array{T}) where T<:MxComplexNum + +function mxarray(a::Array{T}) where {T<:MxComplexNum} mx = mxarray(T, size(a)) na = length(a) rdat = unsafe_wrap(Array, real_ptr(mx), na) @@ -276,8 +277,30 @@ function mxarray(a::Array{T}) where T<:MxComplexNum mx end -mxarray(a::BitArray) = mxarray(convert(Array{Bool}, a)) -mxarray(a::AbstractRange) = mxarray([a;]) + +function mxarray(a::AbstractArray{T}) where {T<:MxRealNum} + mx = mxarray(T, size(a)) + ptr = data_ptr(mx) + na = length(a) + dat = unsafe_wrap(Array{T}, ptr, na) + for (i, ix) in enumerate(eachindex(a)) + dat[i] = a[ix] + end + return mx +end + +function mxarray(a::AbstractArray{T}) where {T<:MxComplexNum} + mx = mxarray(T, size(a)) + na = length(a) + rdat = unsafe_wrap(Array, real_ptr(mx), na) + idat = unsafe_wrap(Array, imag_ptr(mx), na) + for (i, ix) in enumerate(eachindex(a)) + rdat[i] = real(a[ix]) + idat[i] = imag(a[ix]) + end + return mx +end + # sparse matrix diff --git a/test/mxarray.jl b/test/mxarray.jl index ddf3a3f..b92b1cb 100644 --- a/test/mxarray.jl +++ b/test/mxarray.jl @@ -1,5 +1,6 @@ using MATLAB using Test +using SparseArrays # Unit testing for MxArray @@ -361,6 +362,55 @@ delete(a_mx) @test a == a_jl @test isa(a_jl, SparseMatrixCSC{Complex{Float64}}) +############################## +# Abstract Array Conversions +############################## + +a = transpose(rand(10)) +x = mxarray(a) +y = jvalue(x) +delete(x) +@test isa(y, Array{Float64,2}) +@test size(y) == size(a) +@test isequal(y, a) + +a = rand(10,10) +a_ = @view a[3:7, 4:8] +x = mxarray(a_) +y = jvalue(x) +delete(x) +@test isa(y, Array{Float64,2}) +@test size(y) == size(a_) +@test isequal(y, a_) + +a_ = rand(ComplexF32, 10, 10, 10) +a = @view a_[3:7, 4:8, 2:5] +x = mxarray(a) +y = jvalue(x) +delete(x) +@test isa(y, Array{ComplexF32,3}) +@test size(y) == size(a) + +a = 1:100 # range +x = mxarray(a) +y = jvalue(x) +delete(x) +@test isa(y, Array{Int64,1}) +@test isequal(y, collect(a)) + +a = BitArray(rand(Bool, 5,20,10)) +x = mxarray(a) +y = jvalue(x) +delete(x) +@test isa(y, Array{Bool,3}) +@test isequal(y, a) + + + +############################## +# String Conversions +############################## + a = "MATLAB" x = mxarray(a) y = jvalue(x) diff --git a/test/runtests.jl b/test/runtests.jl index dc83d65..f68549b 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -4,8 +4,8 @@ using Test is_ci() = lowercase(get(ENV, "CI", "false")) == "true" if !is_ci() # only test if not CI -include("engine.jl") -include("matfile.jl") -include("matstr.jl") -include("mxarray.jl") + include("engine.jl") + include("matfile.jl") + include("matstr.jl") + include("mxarray.jl") end