MATLAB: Saving file with file name from user

save file gui

I have code for push button where user will click on save, then a folder browser opens where user selects the folder to save the file.
Now here my code:
filename=('output.xls');
foldername = uigetdir;
% ensure the folder name is valid
if ischar(foldername)
% update the file name to include the folder name
filename = fullfile(foldername,filename);
% open the file
fid = fopen(filename,'w');
if fid>0
% write the data to file
fprintf(fid, '%6s\t%6s\t\n', 'x', 'y');
fprintf(fid, '%6.4f\t%6.41f\t\n', result);
fclose(fid);
end
end
So here by default the output file name will be output.xls
I want to have the user capability to set the name of the file. So how to do that?

Best Answer

Let the user type it in with uiputfile(). Here is my snippet for that:
% Get the name of the file that the user wants to save.
% Note, if you're saving an image you can use imsave() instead of uiputfile().
startingFolder = userpath
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uiputfile(defaultFileName, 'Specify a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)