在 MATLAB 中读取带有逗号小数点分隔符的 txt 文件

Read txt file with comma decimal separator in MATLAB

我有一个这样的 txt 文件:

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

即用“,”代替“.”作为小数点分隔符

如何在 MATLAB 中正确读取此输出:

1.6 2 6 5 ...
0 1 4 2.5 ...
...

没有简单的内置方法可以做到这一点(令人惊讶!)。您需要读入整个文件,然后进行字符串替换,然后将结果转换为数字。

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

this MathWorks Central thread is to use strrep推荐的快捷方式:

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

因此,首先将您的数据读取为字符串,然后将逗号替换为点并使用 str2num 进行双打。

另一种可能性是简单地将文件中的逗号替换为句点,然后在 MATLAB 中加载新文件。

在 Linux 或 Mac 上,我们可以使用 sedtr UNIX 实用程序:

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

在 Windows,我们可以使用 PowerShell:

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

无论如何,我们可以简单地在 MATLAB 中加载新文件:

>> load -ascii file2.dat
>> disp(file2)
    1.6000    2.0000    6.5000    5.0000
         0    1.0000    4.0000    2.5000