Write Cell Array of Strings to Text Document

조회 수: 3 (최근 30일)
John
John 2014년 11월 13일
댓글: Geoff Hayes 2014년 11월 14일
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에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by