Write Cell Array of Strings to Text Document

3 views (last 30 days)
John
John on 13 Nov 2014
Commented: Geoff Hayes on 14 Nov 2014
I tried the following code:
fid = fopen('test.txt','wt');
fprintf(fid,'Data:\n');
myCell = {'A','B','C';'D','E','F'};
formatString = [repmat('%s\t',1,size(myCell,2)-1), '%s\n'];
cellfun(@(x) fprintf(fid,formatString,x),myCell.');
fclose(fid);
expecting to get an array printed out, but instead get:
Data:
A B C D E F
(there's a newline between the colon and letters, html issue)
Just wondering what I'm doing wrong. I can get it to work using a matrix of numbers instead of strings. Tried dlmwrite too. Although that works for THIS example, it does not work on a more complicated array that I am actually working on (still a cell array of strings though. enough comments warned away from DLMWRITE that I abandoned that path).

Answers (1)

Geoff Hayes
Geoff Hayes on 13 Nov 2014
John - your formatString is initialized as
formatString =
%s\t%s\t%s\n
So it is expecting three string inputs but your cellfun function input parameter is only providing one to fprintf
@(x) fprintf(fid,formatString,x)
If you change this to
@(x) fprintf(fid,formatString,x,x,x)
and re-run your code, you will see the file contents has been updated to
Data:
A A A
B B B
C C C
D D D
E E E
F F F
Is this the array that you are expecting?
  2 Comments
John
John on 13 Nov 2014
Edited: John on 13 Nov 2014
Thanks for the help, and that is closer, but what I'm trying to get it just myCell itself, so:
Data:
A B C
D E F
Geoff Hayes
Geoff Hayes on 14 Nov 2014
In that case, you may want to arrayfun instead and operate on each row of myCell instead of each element within the cell array. Try the following
fid = fopen('test.txt','wt');
fprintf(fid,'Data:\n');
myCell = {'A','B','C';'D','E','F'};
formatString = [repmat('%s\t',1,size(myCell,2)-1), '%s\n'];
arrayfun(@(row)fprintf(fid,formatString,myCell{row,:}),1:size(myCell,1));
fclose(fid);
So the only difference is the arrayfun versus the cellfun. Note how we use myCell in the function that writes each row of the cell array to file. Since we want to write out each row, then we need to specify this using 1:size(myCell,1) which is just an array corresponding to each of the rows. (In this example, the array would be [1 2].)
Running the above code writes the following to your text file
Data:
A B C
D E F

Sign in to comment.

Categories

Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!