Skip to content
Prev 239863 / 398500 Next

R and Matlab

Hi.
On Fri, Oct 29, 2010 at 3:31 AM, Claudia Beleites <cbeleites at units.it> wrote:
Yes, it is an unfortunate side effect that if there is an error while
writing the MAT file, it gives a corrupt *.mat file.  I'll put it on
the "to do in the future" list to write to a temporary file (e.g.
*.mat.tmp) which is only renamed to *.mat when writeMat() returns
successfully.  I use that "trick" elsewhere and it has saved us a few
times.
Thanks for spotting that; a merge of (nchar (names) == 0) and (names
== "") incorrectly became (names == 0). Corrected in the next release.
I did think about that, however, it may introduce other ambiguities.
For instance, consider

writeMat("foo.mat", V2=1, 2);

Then there will be two "V2" names.  The analogue to read.table() or
data.frame() is to add ".1" etc when there is a clash, e.g. "V2" and
"V2.1".  However, "V2.1" is not a valid name in Matlab.  What should
then be done?  Of course, you can try to make sure you generate valid
Matlab names.

On a related matter, today you can do writeMat("foo.mat", V2=1,
"V2.1"=2) and there is no warning/error given by writeMat() and it
reads correctly by readMat().  However, in Matlab you get
??? Error using ==> load
Invalid field name: 'V2.1'.

If anyone knows a regular expression for testing the validity of names
such that they are valid Matlab variable/field names, please let me
know and I can add additional sanity checks in writeMat().

Also, as your initial example indicates that it could be surprising
that writeMat("foo.mat", x) would become writeMat("foo.mat", V1=x) and
not writeMat("foo.mat", x=x).

After further investigation, I actually think that although Matlab
indeed can read non-named objects using data=load('foo.mat') I don't
think they are accessible.  So I was wrong.  Because of this, I have
bumped up the warning to be an error, preventing non-named objects to
be written.  Will be the case in the next release of the package.

I will postpone adding any bells and whistles trying to make
writeMat() smart such as adding names.  As soon as you do that you
introduce other issues and expectations and have to worry about
backward compatibilities if it turns out to be a bad idea.  My
strategy for now is to have writeMat() assert that only valid MAT
files are written, and give errors otherwise.

/Henrik