I have a two 100x2 .mat file and I would like to get the elements stored as pairwise entries i.e. something like data = [{a1,b1},{a2,b2}..{a100,b100}]. Can someone help me do this efficiently?
1 Answers
It is not quite clear what you mean when you say "100x2".mat file.
Do you mean you have one piece of data with dimensions 100x2?
If that is the case you can use
data = Import["xxx.mat", "Data"]
where "xxx.mat" is the name of your matlab file (the string "Data" is not needed but makes your intention clear).
The resulting data will be in the desired form but one too many parenthesis. So you need to Flatten it one level.
data = Flatten[Import["xxx.mat", "Data"], 1]
If you have multiple pieces of data you get their names via:
names = Import["xxx.mat", "Labels"];
and then you can see the names using
TableForm[Table[{i, names[[i]]}, {i, Length[names]}]]
Using the Matlab names
In order to import the data and use the same variable names as used in Matlab follow these steps
matlabData = Import["xxx.mat", "Data"];
names = Import["xxx.mat", "Labels"];
Note: One skips the flattening of the imported data in this procedure.
The names are a list of strings. One needs to convert them to symbols. Matlab allows variables to use the underscore character. This is not true for Mathematica ("_" is a shortcut for Blank). In order to take care of these two problems execute:
names = ToExpression[
StringReplace[#, RegularExpression["[_]"] ~~ x_ -> ToUpperCase[x]]
] & /@ names
Now you can assign the data to symbols using the names in the matlab file.
MapThread[Set, {names, matlabData}];
- 14,462
- 2
- 25
- 37
-
Why you do not use Flatten? Like
mma2mat = Flatten[mma, Table[{i}, {i, Depth[mma] - 1, 1, -1}]];here http://mathematica.stackexchange.com/q/10582/9815 – Léo Léopold Hertz 준영 Sep 23 '16 at 10:21 -
I did exactly as you said, but Mathematica throws an error saying "MapThread::mptd: "Object dataValues[{{{1.,2.},{2.,4.},{3.,6.}}}] at position {2, 2} in !(MapThread[Set, {{"x"}, dataValues[{{{1.
, 2.}, {2., 4.}, {3., 6.}}}]}]) has only 0 of required 1 dimensions." " where MapThread[Set, {{"x"}, dataValues[{{{1., 2.}, {2., 4.}, {3., 6.}}}]}] – Suga Dec 29 '16 at 01:46
Import? – Sjoerd C. de Vries Oct 17 '15 at 14:42