How can I save cell array with columns of different lengths into a text file(all numeric data)

39 views (last 30 days)
Georgios Tertikas on 26 Jul 2018
Edited: dpb on 29 Jul 2018
I have a cell array that is 1*12 and each cell has a different amount of numbers eg
cell 1 (22*1 double )
cell 2 (33*1 double)
etc.
The data in each cell are all numbers extrapolated previously from a table array. Do you know of a way to save this file into a text file(preferable tabular form) but in a way that I can access all the data. eg
[2;5;6;13;33;56;76;87;97;64;12](first cell)
[3;14;55;68;200;11111] (second cell)
and so on.
dpb on 28 Jul 2018
Well, is this for visual presentation or for saving to disk for transport or recall? If only to save for later retrieval in Matlab, then save, load is the ticket.
If must be human-readable, can you live with the augmented form for converting to rectangular form?

dpb on 28 Jul 2018
Edited: dpb on 29 Jul 2018
The simpler augmentation route looks something like--
l=cellfun(@length,c); % return length of each cell in cell array c
L=max(l); % and find the longest
n=arrayfun(@(l) nan(L-l,1),l,'uni',0); % create vector of NaN to make each equal length
for i=1:size(c,2) % and make the array uniform
c(i)={[c{i};n{i}]};
end
a=cell2mat(c); % alternatively, now turn to double array
dlmwrite('output.txt',a,',') % one of several choices to write text file
As noted, it's somewhat more complex to avoid writing the extra data for shorter columns; the idea is similar in finding the length, but will then need to sort those lengths and, keeping the index of which is the shorter next, write the records for the columns with data for each record in a loop.
Higher-level output functions for cell arrays is a glaring weakness in the Matlab slate of i/o functions; there's little commend most of the the others in real ease-of-use for any but the most trivial of cases. There are some data import objects to help define text file formats for reading text files that can be quite helpful; unfortunately TMW has not seen fit to make any sort of tool going the other way. The most high-level routine there is is writetable but a table can only be regular, it can't be "jagged", so you're still forced to augment it plus turn everything into a table to begin with to use it...
Well, the last got me wondering just what would writetable do; just maybe it's smarter than I think...
>> l=randi(10,1,4)
l =
2 3 7 5
>> c=arrayfun(@(l) randi(299,l,1),l,'uni',0)
c =
1×4 cell array
{2×1 double} {3×1 double} {7×1 double} {5×1 double}
>> t=cell2table(c)
t =
1×4 table
c1 c2 c3 c4
____________ ____________ ____________ ____________
[2×1 double] [3×1 double] [7×1 double] [5×1 double]
>> writetable(t)
>> type t.txt
c1_1,c1_2,c2_1,c2_2,c2_3,c3_1,c3_2,c3_3,c3_4,c3_5,c3_6,c3_7,c4_1,c4_2,c4_3,c4_4,c4_5
106,249,175,165,275,86,227,226,114,170,23,17,159,233,280,39,171
Well, it works for a particular definition of "working", but probably not the solution you were looking for...