matlab:分隔没有可用特定分隔符的 .csv 文件

matlab: delimit .csv file where no specific delimiter is available

我想知道是否可以读取如下所示的 .csv 文件:

0,0530,0560,0730,.... 90,15090,15290,157....

我应该得到:

0,053 0,056 0,073 0,... 90,150 90,152 90,157 90,...

当使用 dlmread(path, '') matlab 吐出一个错误说 Mismatch between file and Format character vector. Trouble reading 'Numeric' field frin file (row 1, field number 2) ==> ,053 0,056 0,073 ...

我也尝试过使用“0”作为分隔符,但 matlab 禁止这样做。

谢谢, 乔尼克斯

如果您可以访问 GNU / *NIX 命令行,我建议您在输入 matlab 之前使用 sed 预处理 您的数据。在这种情况下,命令将是:sed 's/,[0-9]\{3\}/& /g' .

$ echo "90,15090,15290,157" | sed 's/,[0-9]\{3\}/& /g'

90,150 90,152 90,157

$ echo "0,0530,0560,0730,356" | sed 's/,[0-9]\{3\}/& /g'

0,053 0,056 0,073 0,356

此外,您可以轻松地将逗号 , 更改为小数点 .

$ echo "0,053 0,056 0,073 0,356" | sed 's/,/./g'

0.053 0.056 0.073 0.356
str= importdata('file.csv','');   %importing the data as a cell array of char
for k=1:length(str)               %looping till the last line
    str{k}=myfunc(str{k});        %applying the required operation
end

哪里

function new=myfunc(str)
  old = str(1:regexp(str, ',', 'once'));  %finding the characters till the first comma
                                              %old is the pattern of the current line
  new=strrep(str,old,[' ',old]);  %adding a space before that pattern
  new=new(2:end);                 %removing the space at the start
end

file.csv

0,0530,0560,073
90,15090,15290,157

输出:

>> str

str=

    '0,053 0,056 0,073'
    '90,150 90,152 90,157'

您实际上可以使用 textscan 执行此操作,无需任何循环并使用一些基本的字符串操作函数:

fid = fopen('no_delim.csv', 'r');
C = textscan(fid, ['%[0123456789' 10 13 ']%[,]%3c'], 'EndOfLine', '');
fclose(fid);
C = strcat(C{:});
output = strtrim(strsplit(sprintf('%s ', C{:}), {'\n' '\r'})).';

以及使用示例输入文件的输出:

output =

  2×1 cell array

    '0,053 0,056 0,073'
    '90,150 90,152 90,157'


它是如何工作的...

format string 指定从文件中重复读取 3 项:

  • 包含从 0 到 9 的任意数量的字符、换行符(ASCII 代码 10)或回车符的字符串 returns(ASCII 代码 13)。
  • 一个逗号。
  • 三个独立的角色。

每组 3 个项目 concatenated, then all sets are printed to a string separated by spaces. The string is split at any newlines or carriage returns to create a cell array of strings, and any spaces on the ends are removed