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).
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!