1

I've got a bunch of .dat files, where the decimal separator is comma instead of dot. Is there any function in MATLAB to set comma as the separator?

mdml
  • 22,442
  • 8
  • 58
  • 66
lnk
  • 593
  • 2
  • 11
  • 27
  • 1
    How are you going to read those files into Matlab? – Luis Mendo Dec 12 '13 at 22:45
  • @lnk The referenced "duplicate" suggests to use some third-party `txt2mat` program, which is probably serious overkill. See my answer for a simple way of converting the text data you have read into a cell array. – chappjc Dec 17 '13 at 22:45

1 Answers1

2

You will have to read the data in as text (with textscan, textread, dlmread, etc.) and convert to numeric.

Say you have read the data into a cell array with each number in a cell:

>> C = {'1,2345','3,14159','2,7183','1,4142','0,7071'}
C = 
    '1,2345'    '3,14159'    '2,7183'    '1,4142'    '0,7071'

Use strrep and str2double as follows:

>> x = str2double(strrep(C,',','.'))
x =
    1.2345    3.1416    2.7183    1.4142    0.7071

For your example data from comments, you have a file "1.dat" formatted similarly to:

1,2 3,4
5,6 7,8

Here you have a space as a delimiter. By default, textscan uses whitespace as a delimiter, so that is fine. All you need to change below is the format specifier for the number of columns in your data by repeating %s for each column (e.g. here we need '%s%s' for two columns):

>> fid = fopen('1.dat','r');
>> C = textscan(fid,'%s%s')
C = 
    {2x1 cell}    {2x1 cell}
>> fclose(fid);

The output of textscan is a cell array for each column delimited by whitespace. Combine the columns into a single cell array and run the commands to convert to numeric:

>> C = [C{:}]
C = 
    '1,2'    '3,4'
    '5,6'    '7,8'
>> x = str2double(strrep(C,',','.'))
x =
    1.2000    3.4000
    5.6000    7.8000
Community
  • 1
  • 1
chappjc
  • 30,359
  • 6
  • 75
  • 132
  • So, I have file 1.dat which contains: – lnk Dec 13 '13 at 11:20
  • two rows:1,2 3,4 '\r'5,6 7,8 I want to obtain matrix M=[1.2 3.4; 3.4 7.8;]. With function csvread('1.dat') I obtain: 1 2 3; 4 0 0 – lnk Dec 13 '13 at 11:35
  • @lnk As the name implies, `csvread` uses commas as a delimiter between values, so you do not want to use that function. Use `textscan` instead, see updates answer. – chappjc Dec 13 '13 at 16:35
  • @lnk Can you accept the answer if this did what you needed? Thanks. :) – chappjc Dec 23 '13 at 22:28
  • Just today figured out how to accept answers)) – lnk Jan 21 '14 at 12:33