Question

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,
Was it helpful?

Solution

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)

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top