MATLAB: Error when trying to write in an external file

file identifierfopenfprintfMATLAB

In the workspace when I do:
>> fid = fopen('aa.txt', 'w');
>> fprintf(fid, 'test \n');
the answer is:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.

Best Answer

You do not have permission to create a new file in your current directory. Use the MATLAB command
pwd
to see which folder you are in.
Note that if you are using MS Windows and you started up MATLAB by clicking on an icon, then your initial directory will be the one that the MATLAB executable itself is installed in. You can change that in MS Windows by changing the properties of the icon.
Note that if you are using OS-X or Linux there may be similar issues as to what directory you start out in.
You should either use the MATLAB command
cd
to change to a different directory, or you should use a full path to create the filename to write to. You may wish to use uiputfile() to prompt the user for the destination file name.
[filename, filepath] = uiputfile('Where do you want to write the file?');
complete_name = fullfile(filepath, filename);
fid = fopen(complete_name, 'w');