开发者

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

I am t开发者_如何学运维rying 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.


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.


I can't really explain the behavior but in order to be able to read the files in Mathematica it is better to specify the Matlab version you are using. In MATLAB try the saving data with version 6.

>> save('test.mat', '-v6', 'data')

Then in mathematica:

In[1]:= Import["test.mat", "LabeledData"]
Out[1]= {"data" -> {"x" -> {{1.}}, "y" -> {{2.}}, "z" -> {{3.}}}, {{2.}}, {{4.}}, {{6.}}, {{3.}}, {{6.}}, {{9.}}, {{4.}}, {{8.}}, {{12.}}, {{5.}}, {{10.}}, {{15.}}, {{6.}}, {{12.}}, {{18.}}, {{7.}}, {{14.}}, {{21.}}, {{8.}}, {{16.}}, {{24.}}, {{9.}},{{18.}}, {{27.}}, {{10.}}, {{20.}}, {{30.}}}

I tried saving with v4 but that doesn't work in MATLAB. Notice that the documentation in Mathematica says that "Import fully supports Versions 4 and 5 of the MAT format.". I Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜