write cell array of strings in text file

I would like to save my cell array of strings in a *.txt file. A simple way is like the following:
filePh = fopen('features_.txt','w');
[rows,cols]=size(Strings);
for r=1:rows
fprintf(filePh,'%s\n',Strings{r,1};
end
So, each cell that is a string (like a sentence...) in one row. But some strings are not very well defined. for example in one string there might be two whitespace between words, or even a tab. Then this code separates the strings in to different rows.
Does anyone know the solution?
Thank you very much in advance

 Risposta accettata

filePh = fopen('features.txt','w');
fprintf(filePh,'%s\n',Strings{:});
fclose(filePh);

8 Commenti

sh as
sh as il 15 Apr 2016
Modificato: sh as il 15 Apr 2016
Thank you for the reply.
I am struggling with different type of files for a simple task, as you see...
This code still did not solve the problem. An example is the rows 6625,6631... in the attached file...
Your cell has 2 columns. Your original question was stated for a single column. For the attached data:
features_score = features_score';
filePh = fopen('features.csv','w');
fprintf(filePh,'%s,%s\n',features_score{:});
fclose(filePh);
Thanks a lot for reply.
It seems I am going toward the solution.
In fact I would like to save the whole of cell array "features_score" in to *xls/csv file, in which first column of file is for strings and the second column is numeric values. beside your solution, there is another problem that some strings do not fit in one row and take 2 rows...
You're data really needs to be cleaned before exporting to a file. There are lots of double spaces and tabs that create accidental line breaks in fprintf.
Here are two extra lines to remove double spaces, tabs, and leading/trailing white space:
cleanData = features_score';
cleanData = regexprep(cleanData,'(\s|\t)+',' ');
cleanData = strtrim(cleanData);
filePh = fopen('features.csv','w');
fprintf(filePh,'%s,%s\n',cleanData{:});
fclose(filePh);
Ah, thank you very much. It worked. Just I moved this code to *.txt file, that is OK.
But, If I want to save them in csv file, then the 2 columns of my cell array, are just added in one column in csv file. I mean they are not in a separate columns in *.csv ...
Kirby Fears
Kirby Fears il 15 Apr 2016
Modificato: Kirby Fears il 15 Apr 2016
Perhaps .csv is ambiguous in your operating system, I don't know.
When I write to .csv, it works fine. The columns are separated by a comma. It opens in Excel as two separate columns.
Strange! and, thanks a lot for your help.
Well, for me ';' separated the columns

Accedi per commentare.

Più risposte (0)

Categorie

Richiesto:

il 15 Apr 2016

Commentato:

il 15 Apr 2016

Community Treasure Hunt

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

Start Hunting!

Translated by