Octaviour
Octaviour

Reputation: 805

detect whether .m file is matlab or mathematica

I have been editing Matlab script in Vim for some time now. Recently I started taking an interest in moving my Mathematica work to plain text files so they can be managed using git and edited using Vim. Unfortunately Mathematica also uses the .m extension for its package files and is therefore not easily distinguished from Matlab scripts. Since I would like my editor to do the work for me I was wondering if anyone has come up with an idea for identifying both based on the contents of the file. I would be fine with something that works in most cases, but am reluctant to use a solution that requires alterations in the scripts such as adding a comment.

Upvotes: 2

Views: 698

Answers (1)

Malte
Malte

Reputation: 31

A ".mat" or ".m" file created with MATLAB's save() function will always start with the plain text identifier "MATLAB". So, using MATLAB syntax, you might do this:

% Set up a workspace variable and save to file
tmp = 1:10;
save('test.m');

% Open the file, read the first line and close again
fid=fopen('test.m');
firstline=fgetl(fid);
fclose(fid);

% Branch depending on file format
if ((numel(firstline) >= 6) && strcmp(firstline(1:6), 'MATLAB'))
    disp('This may well be a MATLAB file.');
else
    disp('This is probably not a MATLAB file.');
end

Upvotes: 1

Related Questions