Search code examples
matlabcommand-line-interface

Convert .m file into .mlx file from command window


I know that .m files (in particular, function files) can be converted to .mlx files (preserving code comments and formatting) by right clicking the file and selecting 'Open as Live Script'.

Is it possible to also generate (and save) the same data as a Live Script/Live Function using the command line?


Solution

  • You can open a string of code as a live script using the matlab.internal.liveeditor.openAsLiveCode. To convert from a .m file you can use fileread first to create that string from the .m file.

    The below was tested in R2022b.

    filepath = 'C:\foo\untitled.m'; % some .m file we want to convert
    matlab.internal.liveeditor.openAsLiveCode(fileread(filepath)); % open as live script
    

    It's slightly painful to save the file because the opening function above doesn't return a handle to the newly opened document. We can get the active document from the matlab.desktop class and then save it:

    activeDoc = matlab.desktop.editor.getActive(); % get the active editor (the new file)
    activeDoc.saveAs( strrep(filepath,'.m','.mlx') ); % Save with same file name but .mlx
    

    If you want to close the new editor window you can do activeDoc.close()

    Result:

    conversion output