MATLAB: Saving the selected .mat file and write it into csv

MATLAB

Hello there,
I was implmenting something similar from this post: https://www.mathworks.com/matlabcentral/answers/317297-uigetfile-load-m-file-variables-into-workspace and I want to get the selected .mat file and write it into csv. I have the following but I have the problem of saving it into .csv file
[baseFileName, folder] = uigetfile('*.mat');
fullFileName = fullfile(folder, baseFileName);
if exist(fullFileName, 'file')
storedStructure = load(fullFileName);
else
warningMessage = sprintf('Warning: mat file does not exist:\n%s', fullFileName);
uiwait(errordlg(warningMessage));
return;
end
cHeader = {'x' 'y' 'z'}; %dummy header
commaHeader = [cHeader;repmat({','},1,numel(cHeader))]; %insert commaas
commaHeader = commaHeader(:)';
textHeader = cell2mat(commaHeader); %cHeader in text with commas
%write header to file
%write data and save it to .csv
fid = fopen(fullFileName,'w');
fprintf(fid,'%s \n',textHeader);
fclose(fid);
dlmwrite(fullFileName,storedStructure.data,'-append');
I think I have problem in the secotion of %write data and save it to .csv using fullFileName. I do not know how to do it properly since we do not have one fixed file to write into. Thanks!

Best Answer

Assuming that storedStructure.data is a matrix with 3 columns, the simplest way to save to csv is with:
writetable(array2table(storedStructure.data, 'VariableNames', {'x', 'y', 'z'}), fullfilename, 'FileType', 'text');
Note that I would recommend changing the extension of the filename from .mat to .csv so that it's not misleading.
Related Question