2

I have a txt file as such:

1,6 2 6,5 5 ...  // ~ 1000 columns 
0 1 4 2,5 ...
... // ~1000 rows

that is, "," as a decimal separator instead of "."

How to read this properly in MATLAB to output as such:

1.6 2 6 5 ...
0 1 4 2.5 ...
...
Amro
  • 123,847
  • 25
  • 243
  • 454
delkov
  • 301
  • 3
  • 15

3 Answers3

1

There is no easy built-in way of doing this (surprisingly!). You'll want to read in the entire file, then do a string replacement, and then convert the result into numbers.

% Read file in as a series of strings
fid = fopen('data.txt', 'rb');
strings = textscan(fid, '%s', 'Delimiter', '');
fclose(fid);

% Replace all commas with decimal points
decimal_strings = regexprep(strings{1}, ',', '.');

% Convert to doubles and join all rows together
data = cellfun(@str2num, decimal_strings, 'uni', 0);
data = cat(1, data{:});
Suever
  • 64,497
  • 14
  • 82
  • 101
  • Isn't there? This is the default decimal separator of a lot of (non-USA) countries. – Adriaan Mar 19 '16 at 15:48
  • @Adriaan Not that I know of. Commas can be a little tricky since they are also typically use as delimiters. I think that even though they are used a decimal separators on the UI side of a lot of programs, most exported data actually uses periods (except Excel). – Suever Mar 19 '16 at 15:59
  • 1
    Yea, Excel indeed uses whatever your system-setting is. And that means locale setting, not language. Pain in the butt actually. SO another solution to this would be to load it in Excel and click three buttons in the dialogue to convert them, but who wants to use Excel anyway. I'd say your solution is a good one. – Adriaan Mar 19 '16 at 16:02
  • perfect! Don't you know how obtain the count of colums? – delkov Mar 19 '16 at 16:09
  • @delkov Check my update. You no longer need to know # of columns if you used the updated approach – Suever Mar 19 '16 at 16:09
  • @Suever no that it matters much, but you probably want to open the file in text mode `rt` instead (supposed to correctly handle LF/CRLF line endings) – Amro Mar 20 '16 at 23:45
0

A quick way suggested by this MathWorks Central thread is to use strrep:

data=strrep(data,'.',',')

So first read your data as strings, then replace commas with dots and use str2num to go to doubles.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
0

Another possibility is simply replacing commas with periods in your file, then load the new file in MATLAB.

On Linux or Mac, we can use sed or tr UNIX utilities:

$ cat file.dat | tr ',' '.' > file2.dat

On Windows, we can use PowerShell:

PS> gc file.dat | % { $_ -replace ',', '.' } | sc -encoding ascii file2.dat

Eitherway, we can load the new file in MATLAB simply as:

>> load -ascii file2.dat
>> disp(file2)
    1.6000    2.0000    6.5000    5.0000
         0    1.0000    4.0000    2.5000
Amro
  • 123,847
  • 25
  • 243
  • 454