Mixed data cell array export problem
3 views (last 30 days)
Show older comments
Okay,
I have a 1x187 cell i'm working with that has column headings as the 1st 4 cells then other stuff after:
newstart= 'ID' 'Date' 'Structure' 'Side' 'F_108' 'F_107' 'F_106.....etc
now I need to output this to either an excel spreadsheet, or preferably for the time being (on a mac) to a .txt or .dat file. Everytime I export it to .csv it delimits each term between every letter and number. It gives every character its own cell.
thus, A1=I A2=D A3=D A4=a A5=t ...etc
I just need a good way to keep each term together as I export it.
Any help would be great, THANKS!
0 Comments
Answers (1)
Guillaume
on 16 Oct 2014
Amongst matlab's high level functions only xlswrite can write a cell array of strings.
You can either use low level functions to write your cell array ( fopen / fprintf / fclose ) or convert it to a table that you can write with writetable.
Either way, the first thing I would do is reshape your cell array to better reflect your data structure. Since you have 4 columns, I would reshape it as an m x 4 cell array. I don't understand why the number of elements is not a multiple of 4, assuming it is:
shapedstart = reshape(newstart, 4, [])';
You can then convert it into a table with cell2table:
tablestart = cell2table(shapedstart(2:end, :), 'VariableNames', shapedstart(1, :));
And finally write it with writetable:
writetable(tablestart, 'somefile.txt');
2 Comments
Guillaume
on 16 Oct 2014
As I said, cvswrite, dlmwrite are not designed to write strings. The output you get with cvswrite is what it's designed to do. I agree it's daft, but there's no way around it.
My answer does not change, either use low level functions, or convert your cell array into a table. If your array is just a row vector, either is very easy:
%low level functions / option 1:
fid = fopen('somefile.txt', 'rt')
fprintf(fid, strjoin(newstart, ','));
fclose(fid);
%low level function / option 2 more generic
fid = fopen('somefile.txt', 'rt')
for row = 1:size(newstart, 1)
for col = 1:size(newstart, 2)-1
fprintf(fid, '%s,', newstart{row, col});
end
fprintf(fid, '%s\n', newstart{row, end});
end
fclose(fid);
%table conversion
writetable(cell2table(newstart), 'somefile.txt');
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!