3
$\begingroup$

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?

$\endgroup$
2

1 Answer 1

4
$\begingroup$

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}];
$\endgroup$
2
  • $\begingroup$ Why you do not use Flatten? Like mma2mat = Flatten[mma, Table[{i}, {i, Depth[mma] - 1, 1, -1}]]; here mathematica.stackexchange.com/q/10582/9815 $\endgroup$ Sep 23, 2016 at 10:21
  • $\begingroup$ 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.}}}]}] $\endgroup$
    – Suga
    Dec 29, 2016 at 1:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.