Search code examples
matlabsaveworkspace

Error using "save" to save in a directory


I would like to save a workspace in another directory and I have written the following in Matlab for it:

fileName = [datestr(now, 'dd-mmm-yyyy_HHMMSS') '_test'];
save('C:\Users\User\project',fileName)

It gives me the error: Error using save: '05-Nov-2019_083736_test' is not a valid variable name.

But if I run without giving an address of the directory it workes perfectly.

Why does it happen?


Solution

  • You can either use il_raffa's suggestion from the comments (with a small correction):

    save(['C:\Users\User\project\' fileName])
    %                           ^ add a folder separator here
    

    or use the fullfile function, to avoid errors due to forgotten folder separators:

    save(fullfile('C:\Users\User\project', fileName));
    

    This works also for subfolders and filenames, e.g.

    save(fullfile('C:\Users\User\project', 'matfiles', fileName));