1

I am trying to create a file to be read in a matlab enviroment. The structure in matlab looks like this

trx(1) = 
          x: [1×1500 double]
          y: [1×1500 double]
          a: [1×1500 double]
          b: [1×1500 double]
      theta: [1×1500 double]
 firstframe: 1
   endframe: 1500
    nframes: 1500
        off: 0 


 trx(2) = 
          x: [1×751 double]
          y: [1×751 double]
          a: [1×751 double]
          b: [1×751 double]
      theta: [1×751 double]
 firstframe: 750
   endframe: 1500
    nframes: 751
        off: -749 

So naturally I created a python dictionary with the required fields and create a list, then used savemat. However when I loaded in matlab I only get cell arrays. I also tried using this but the problem is that not all of the fields are arrays with the same shapes for example 'firstframe' is an int. Then when I used fromarrays() but it complains because the shape does not match.

I am trying now to convert a dictionary to an structured array, but have not found anything related. And also trying to create a numpy record that allows different shapes for the arrays. Any light very welcome

2
  • 1
    The mapping between Python objects and MATLAB is tricky. You might try creating a sample in MATLAB, save it, and then loadmat. That should give a clearer idea of what MATLAB needs. Commented Feb 8, 2019 at 18:42
  • I'm a little rusty on this, but I think MATLAB matrix maps onto a order F ndarray. A cell onto an object dtype array. A struct on to a structured array (i.e. one with a compound dtype, record array in your link). The arrays that go into a structured array do have to match in shape. Commented Feb 8, 2019 at 18:43

1 Answer 1

2

In Octave

M =

  scalar structure containing the fields:

    x =

       1   2   3   4

    y =

       5   6   7   8

    one =  1
    two =

       1   2

>> save -7 struct.mat M

In Ipython:

In [450]: dat = io.loadmat('struct.mat')
In [451]: dat
Out[451]: 
{'__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.2.2, 2019-02-08 18:49:49 UTC',
 '__version__': '1.0',
 '__globals__': [],
 'M': array([[(array([[1., 2., 3., 4.]]), array([[5., 6., 7., 8.]]), array([[1.]]), array([[1., 2.]]))]],
       dtype=[('x', 'O'), ('y', 'O'), ('one', 'O'), ('two', 'O')])}

Here M is (1,1) structured array, with all fields being object dtype. That way they can each have their own shape. The scalar is a (1,1) matrix.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey hpaulji your answer really moved me closer. Now I am stuck with this problem . When I try to recreate the object : Setting void-array with object members using buffer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.