0

I'm looking to separate strings in a text file with commas in Matlab, so far I've used "csvwrite" and "dlmwrite".

They generally take this form:

myFile - input ('Please enter file's directory','s');
readMatrix - csvread(myFile);
csvwrite('newdatafile.dat', readMatrix);

To clarify, what I am trying to do is this :

Turn a text file that looks like this:

0.3
0.1
0.5
etc

To This:

0.3,
0.1,
0.5,
etc,
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Tony Hematite
  • 149
  • 3
  • 14
  • +1 for posting sample input and output. But more importantly you should include a little bit about what exactly it is that's not working. Also in this case you could give some more details about how you're inputting the file and storing it. – Ansari May 12 '12 at 17:47
  • what format does readMatrix have after you read the original file? Is it a matrix (and if so, what size?), or a cell array? – tmpearce May 12 '12 at 18:23

2 Answers2

0

MATLAB's csvwrite function writes matrix data into a file separated by commas. Strings unfortunately in MATLAB don't have their own separate data type and are also represented as matrices, so when you run csvwrite on them they will treat each letter as an element and put a comma between each letter.

You have two options: Either store your input as doubles and run csvwrite on that, or use more primitive functions to output them to a file (sprintf followed by fprintf to a file handle).

Ansari
  • 8,168
  • 2
  • 23
  • 34
0

Why do you need the commas at the end of the line? csvread works also with a file of which the rows contain comma-separated numbers, i.e.:

file1.dat:
02, 04, 06, 08, 10, 12
03, 06, 09, 12, 15, 18
05, 10, 15, 20, 25, 30
07, 14, 21, 28, 35, 42
11, 22, 33, 44, 55, 66


--and then in matlab:
readMatrix = csvread('file1.dat')

will read the file and result in size(readMatrix) = [5 6] (despite the missing comma at the end of each line) Same thing applies if the file only contains one column of numbers (and hence no commas).

If you however really want the commas, you can read the data and print it to a file yourself with fprintf:

readMatrix = csvread('file1.dat');
fid=fopen('file1withcommas.dat','w');
for ii=1:size(readMatrix,1)
    fprintf(fid,'%g,\n',readMatrix(ii,:));
end
fclose(fid)
Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58