Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import[] for MAT file containing struct arrays - Only imports first element?

I am trying to import data from a saved MATLAB struct array, but it seems that Mathematica is only importing the first element.

MATLAB

blank = struct('x', [], 'y', [], 'z', []);
data = repmat(blank, 1, 10);

for i = 1:10
    data(i) = struct('x', i, 'y', i * 2, 'z', i * 3);
end

save('test.mat', 'data');

Mathematica

In[76]:= Import["test.mat", "LabeledData"]
Out[76]= {"data" -> {"x" -> {{1.}}, "y" -> {{2.}}, "z" -> {{3.}}}}

Does anyone know why this is happening?

As a temporary fix, I've simply resorted to storing multiple struct's in a cell array, i.e.

data{i} = struct(...)

Mathematica seems to be able to handle that fine.

like image 703
eacousineau Avatar asked Nov 04 '22 19:11

eacousineau


1 Answers

There is a Mathematica package for interfacing with MATLAB that can transfer structs from MATLAB. See here: MATLink.

This is how you do the transfer in MATLink:

Needs["MATLink`"]

MEvaluate["
 blank = struct('x', [], 'y', [], 'z', []);
 data = repmat(blank, 1, 10);

 for i = 1:10
     data(i) = struct('x', i, 'y', i * 2, 'z', i * 3);
 end"]

MGet["data"]

{{"x" -> 1., "y" -> 2., "z" -> 3.}, {"x" -> 2., "y" -> 4., 
  "z" -> 6.}, {"x" -> 3., "y" -> 6., "z" -> 9.}, {"x" -> 4., 
  "y" -> 8., "z" -> 12.}, {"x" -> 5., "y" -> 10., 
  "z" -> 15.}, {"x" -> 6., "y" -> 12., "z" -> 18.}, {"x" -> 7., 
  "y" -> 14., "z" -> 21.}, {"x" -> 8., "y" -> 16., 
  "z" -> 24.}, {"x" -> 9., "y" -> 18., "z" -> 27.}, {"x" -> 10., 
  "y" -> 20., "z" -> 30.}}

Disclaimer: I am one of the MATLink developers.

like image 111
Szabolcs Avatar answered Nov 09 '22 10:11

Szabolcs