Read txt file with comma decimal separator in MATLAB [duplicate]

天涯浪子 提交于 2019-12-01 22:53:49

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{:});

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!