Write Cell Array of Strings to Text Document

3 vues (au cours des 30 derniers jours)
John
John le 13 Nov 2014
Commenté : Geoff Hayes le 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).

Réponses (1)

Geoff Hayes
Geoff Hayes le 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 commentaires
John
John le 13 Nov 2014
Modifié(e) : John le 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 le 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by