Skip to content

Commit faf874e

Browse files
committed
Add conversion for tuples
1 parent 8183663 commit faf874e

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/mxarray.jl

+31-1
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ function mxarray(a::AbstractArray{T}) where {T<:MxRealNum}
289289
return mx
290290
end
291291

292-
function mxarray(a::AbstractArray{T}) where {T<:MxComplexNum}
292+
function mxarray(a::AbstractArray{T}) where {T <: MxComplexNum}
293293
mx = mxarray(T, size(a))
294294
na = length(a)
295295
rdat = unsafe_wrap(Array, real_ptr(mx), na)
@@ -302,6 +302,36 @@ function mxarray(a::AbstractArray{T}) where {T<:MxComplexNum}
302302
end
303303

304304

305+
function mxarray(a::NTuple{N, T}) where {N, T <: MxRealNum}
306+
mx = mxarray(T, N)
307+
pdat = ccall(mx_get_data[], Ptr{T}, (Ptr{Cvoid},), mx)
308+
dat = unsafe_wrap(Array, pdat, N)
309+
for i in 1:N
310+
dat[i] = a[i]
311+
end
312+
return mx
313+
end
314+
315+
function mxarray(a::NTuple{N, T}) where {N, T <: MxComplexNum}
316+
mx = mxarray(T, size(a))
317+
na = length(a)
318+
rdat = unsafe_wrap(Array, real_ptr(mx), na)
319+
idat = unsafe_wrap(Array, imag_ptr(mx), na)
320+
for (i, ix) in enumerate(eachindex(a))
321+
rdat[i] = real(a[ix])
322+
idat[i] = imag(a[ix])
323+
end
324+
return mx
325+
end
326+
327+
function mxarray(a::Tuple)
328+
mx = mxcellarray(length(a))
329+
for i in 1:length(a)
330+
set_cell(mx, i, mxarray(a[i]))
331+
end
332+
return mx
333+
end
334+
305335
# sparse matrix
306336

307337
function mxsparse(ty::Type{Float64}, m::Integer, n::Integer, nzmax::Integer)

test/mxarray.jl

+22
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,28 @@ delete(x)
405405
@test isa(y, Array{Bool,3})
406406
@test isequal(y, a)
407407

408+
# Issue: Tuples converted to MATLAB structs
409+
# https://github.com/JuliaInterop/MATLAB.jl/issues/178
410+
a = (2.5, 2.6)
411+
x = mxarray(a)
412+
y = jvalue(x)
413+
@test classid(x) == MATLAB.mxDOUBLE_CLASS
414+
@test nrows(x) == 2
415+
@test ncols(x) == 1
416+
delete(x)
417+
@test isa(y, Vector{Float64})
418+
@test isequal(y, collect(a))
419+
420+
# Tuple with mixed types
421+
a = (1, 2.0, "MATLAB", [1, 2, 3])
422+
x = mxarray(a)
423+
y = jvalue(x)
424+
@test nrows(x) == 4
425+
@test ncols(x) == 1
426+
@test classid(x) == MATLAB.mxCELL_CLASS
427+
@test isa(y, Vector{Any})
428+
@test length(y) == length(a)
429+
@test isequal(y, collect(a))
408430

409431

410432
##############################

0 commit comments

Comments
 (0)