Write Cell Array of Strings to Text Document

1 次查看(过去 30 天)
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).

回答(1 个)

Geoff Hayes
Geoff Hayes 2014-11-13
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 个评论
John
John 2014-11-13
编辑:John 2014-11-13
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 2014-11-14
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by