ndb
ndb

Reputation: 137

How to prevent matlab from automatically separating a string with commas to different cells in csv?

I have a huge cell array, called A, full of strings like this:

'Watson J. D., Crick F. H., (April 1953)., Molecular Structure of nucleic acids'
'Watson J. D., Crick F. H., (April 1953)., Molecular Structure of nucleic acids'
'Special_Relativity_By_Einstein'
'Special_Relativity_By_Einstein'
'Edgar, R. S., Feynman, Richard P., Klein, S., Lielausis, I., Steinberg, CM (1962) Mapping Experiments...'

And I want to write this cell array automatically into a xls or csv file into ONE column.

The problem is that when I want to write A into a csv file using a technique such as

fid = fopen('NamesOfPapers.csv','w');
for i=1:length(A)
    fprintf(fid,'%s\n', A{i});
end
fclose(fid);

for example, I get multiple columns for this line:

Watson J. D., Crick F. H., (April 1953)., Molecular Structure of nucleic acids

Special_Relativity_By_Einstein will just occupy Row 3, col 1, the way I want it to.

How do I get strings such as

Watson J. D., Crick F. H., (April 1953)., Molecular Structure of nucleic acids

To occupy just one column in my csv file, not multiple columns on the same row? I do not want it to be automatically split into multiple columns.

I'm using a MacBookPro to do this by the way. Thanks!

Upvotes: 2

Views: 255

Answers (1)

Jonas
Jonas

Reputation: 74940

Open the .csv file in a text editor. You'll see that it looks just fine.

The problem occurs when you open the .csv file in Excel. Excel looks at the .csv file (the extension stands for "comma-separated value"), and interprets the commas as indicators to start a new column.

To avoid that, enclose each row in quotation marks, so that Excel correctly interprets the data.

fid = fopen('NamesOfPapers.csv','w');
for i=1:length(A)
    fprintf(fid,'"%s"\n', A{i});
end
fclose(fid);

Upvotes: 1

Related Questions