MATLAB: Export of Cell-Arrays to more than one txt-file

cell arraydata exportfprintfmatrices

Have a Cell Array XX with the dimension of 31 * 10 and each XX{i,j} consists of 1000 rows and 31 columns. These 1000 lines and 31 columns should end up in a respective txt-file.
For this I have tried to:
save(file_name_xc,'XX','-ascii');
header = '%alb_newsnow alb_oldsnow alb_decrease alb_firn alb_ice alb_shallowpack_ice alb_shallowpack_rock crit_swe_newsnow crit_swe_shallowpack snow_cf temp_wetbulb_lthr temp_wetbulb_uthr clmaxn slope_min slope_max slope_cf curv_max cwh_snow cwh_firn cch refree n_snow k_snow n_firn k_firn n_ice k_ice n_rock k_rock n_soil k_soil';
formattype = '' ; for i=1:M-1; formattype = [ formattype '%g\t' ]; end; formattype = [ formattype '%g\n' ];
% open the file with status write
fid = fopen(file_name_xc,'w') ;
% write the header
fprintf(fid,'%s\n',header);
% write -> cell-string
[nrows,ncols] = size(XX);
for row = 1:nrows
fprintf(fid,formattype,XX);
end
fclose(fid);
The following error message appeared:
Warning: Attempt to write an unsupported data type to an ASCII file. Variable 'XX' not written to file. > In write_to_file at 209
Line 209 includes the code save(file_name_xc,'','-ascii).
Based on this, I tried to convert the cell-array into a matrix before I used the save(…), with
XX = cell2mat(XX);
In this case, all rows and columns are written to a single matrix and to a single txt file.
How can one write each XX {} into a separate txt-file, which consists of 1000 lines and 31 columns?
Thanks

Best Answer

Well, yes, that first line you show will cause an error since you attempt to write the whole cell array (the 310 matrices) into a single file, and matlab does not know how to do this.
Nowhere in your code is there a loop to go over each of the files you want to write, so I'm a bit unclear why you expected any of it to work.
Considering that there are a lot more efficient tools than fprintf to write a matrix all at once into a text file, this is how I'd do it:
columnnames = {'alb_newsnow', 'alb_oldsnow', 'alb_decrease', 'alb_firn', 'alb_ice', 'alb_shallowpack_ice', 'alb_shallowpack_rock', 'crit_swe_newsnow', 'crit_swe_shallowpack', 'snow_cf', 'temp_wetbulb_lthr', 'temp_wetbulb_uthr', 'clmaxn', 'slope_min', 'slope_max', 'slope_cf', 'curv_max', 'cwh_snow', 'cwh_firn', 'cch', 'refree', 'n_snow', 'k_snow', 'n_firn', 'k_firn', 'n_ice', 'k_ice', 'n_rock', 'k_rock', 'n_soil', 'k_soil'};
folder = 'C:\somewhere';
nameprefix = 'somename';
for col = 1:size(XX, 2) %note that XX is a completely useless name
for row = 1:size(XX, 1)
fullpath = fullfile(folder, sprintf('%s_%02d_%02d.txt', nameprefix, row, col)); %build file name however you want
temptable = array2table(XX{row, col}, 'VariableNames', columnnames); %convert matrix to table
writetable(temptable, fullpath, 'Delimiter', 'tab'); and write into file in one go
end
end