Skip to content

Commit

Permalink
Merge pull request JuliaInterop#231 from tqml/feature/add-tuple-conve…
Browse files Browse the repository at this point in the history
…rstion

Add conversion for tuples
  • Loading branch information
tqml authored Feb 9, 2025
2 parents b37b3aa + faf874e commit af76a18
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/mxarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ function mxarray(a::AbstractArray{T}) where {T<:MxRealNum}
return mx
end

function mxarray(a::AbstractArray{T}) where {T<:MxComplexNum}
function mxarray(a::AbstractArray{T}) where {T <: MxComplexNum}
mx = mxarray(T, size(a))
na = length(a)
rdat = unsafe_wrap(Array, real_ptr(mx), na)
Expand All @@ -302,6 +302,36 @@ function mxarray(a::AbstractArray{T}) where {T<:MxComplexNum}
end


function mxarray(a::NTuple{N, T}) where {N, T <: MxRealNum}
mx = mxarray(T, N)
pdat = ccall(mx_get_data[], Ptr{T}, (Ptr{Cvoid},), mx)
dat = unsafe_wrap(Array, pdat, N)
for i in 1:N
dat[i] = a[i]
end
return mx
end

function mxarray(a::NTuple{N, T}) where {N, 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

function mxarray(a::Tuple)
mx = mxcellarray(length(a))
for i in 1:length(a)
set_cell(mx, i, mxarray(a[i]))
end
return mx
end

# sparse matrix

function mxsparse(ty::Type{Float64}, m::Integer, n::Integer, nzmax::Integer)
Expand Down
22 changes: 22 additions & 0 deletions test/mxarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,28 @@ delete(x)
@test isa(y, Array{Bool,3})
@test isequal(y, a)

# Issue: Tuples converted to MATLAB structs
# https://github.com/JuliaInterop/MATLAB.jl/issues/178
a = (2.5, 2.6)
x = mxarray(a)
y = jvalue(x)
@test classid(x) == MATLAB.mxDOUBLE_CLASS
@test nrows(x) == 2
@test ncols(x) == 1
delete(x)
@test isa(y, Vector{Float64})
@test isequal(y, collect(a))

# Tuple with mixed types
a = (1, 2.0, "MATLAB", [1, 2, 3])
x = mxarray(a)
y = jvalue(x)
@test nrows(x) == 4
@test ncols(x) == 1
@test classid(x) == MATLAB.mxCELL_CLASS
@test isa(y, Vector{Any})
@test length(y) == length(a)
@test isequal(y, collect(a))


##############################
Expand Down

0 comments on commit af76a18

Please sign in to comment.