Search code examples
matlabunicodesavefilenamesmatlab-figure

Saving a figure using saveas when filename contains a Unicode character


Summary: I would like to save a figure with a filename like σ=0.25.fig, but saving fails.

Elaboration: I'm working with R2019b Update 3 (on Win10), and I cannot modify my MATLAB configuration to allow saving .m files with Unicode characters in them (i.e. feature('DefaultCharacterSet') is stuck on 'US-ASCII'), I'm forced to use sprintf in order to store various non-ASCII symbols in my source files. This usually works well, but apparently it causes problems when trying to use saveas.

Example: Consider the following code,

hF = figure();
saveas( hF, sprintf('\x03C3=%4.2f.fig', 0.25) ) % sprintf correctly resolves to "σ=0.25.fig"

which (on my system?) results in the following error:

Error using save
Unable to write to MAT-file σ=0.25.fig.
The file may be corrupt.
Error in matlab.graphics.internal.figfile.FigFile/write (line 32)
save(obj.Path, obj.MatVersion, '-struct', 'SaveVars');
Error in savefig (line 83)
FF.write();
Error in saveasfig (line 6)
savefig(h, name);
Error in saveas (line 153)
    feval( ['saveas' format], h, name ) 

Question: In light of the above error, how is it possible to save the figure with the desired filename?


Solution

  • Fortunately, the movefile function, which is used for moving or renaming files, does not suffer from the same problem with Unicode paths. Thus, all we need is to split the saving into two steps, where a temporary path/name (consisting of characters that saveas "likes") is initially used, following by moving/renaming to the desired name/path:

    saveas(hF, 'tmp.fig');
    movefile('tmp.fig', fullfile(pwd, sprintf('\x03C3=%4.2f.fig', 0.25)));
    

    ... producing the desired result,

    enter image description here