Skip to content

How to write an array of structs? #206

@matthijscox

Description

@matthijscox

I noticed that I can read normal arrays of structs and cell arrays of structs with MAT.jl, but I cannot write arrays of structs. At least not by default. Would love to know how to do that.

MATLAB input data

Here's an example:

s = struct();
s.array = [struct('x', [1,2], 'y', [3,4]), struct('x', [5,6], 'y', [7,8])];
s.cell = {struct('x', [1,2], 'y', [3,4]), struct('x', [5,6], 'y', [7,8])};
save('struct_test.mat', 's')

This is the input, note that we have a 1x2struct array

>> s

s = 

  struct with fields:

    array: [1×2 struct]
     cell: {[1×1 struct]  [1×1 struct]}

>> s.array

ans =

[1x2 struct, 608 bytes]
x: [1, 2]
y: [3, 4]

Julia conversion

Let's read and write in Julia without editing:

using MAT
vars = matread("struct_test.mat")
matwrite("julia_struct_test.mat", vars)

Note that inside Julia, we already have something unexpected. I expected a struct/dict array for the MATLAB struct array, but instead we get arrays of arrays inside the "x" and "y" keys, e.g. see "x" => Any[[1.0 2.0] [5.0 6.0]].
In the cell array case we do have an array of dicts.

julia> vars["s"]
Dict{String, Any} with 2 entries:
  "array" => Dict{String, Any}("x"=>Any[[1.0 2.0] [5.0 6.0]], "y"=>Any[[3.0 4.0] [7.0 8.0]])
  "cell"  => Any[Dict{String, Any}("x"=>[1.0 2.0], "y"=>[3.0 4.0]) Dict{String, Any}("x"=>[5.0 6.0], "y"=>[

julia> vars["s"]["array"]
Dict{String, Any} with 2 entries:
  "x" => Any[[1.0 2.0] [5.0 6.0]]
  "y" => Any[[3.0 4.0] [7.0 8.0]]

julia> vars["s"]["cell"]
1×2 Matrix{Any}:
 Dict{String, Any}("x"=>[1.0 2.0], "y"=>[3.0 4.0])  Dict{String, Any}("x"=>[5.0 6.0], "y"=>[7.0 8.0])

MATLAB loading

Now loading this data back in MATLAB, we see that we get a [1x1 struct] while originally we had a [1x2 struct]. Now we have cell arrays inside the fields (similar to what we found while loaded in Julia above).
The cell array is unchanged.

>> load("julia_struct_test.mat")

>> s

s = 

  struct with fields:

    array: [1×1 struct]
     cell: {[1×1 struct]  [1×1 struct]}

>> s.array

ans = 

  struct with fields:

    x: {[1 2]  [5 6]}
    y: {[3 4]  [7 8]}

Final question

So my main question is: how can I get back the [1x2 struct] in the s.array field? Is that even possible with MAT.jl?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions