在Matlab中读取带有特殊字符的文本文件

3

我有一个 *.txt 的原始数据文件,想要使用Matlab读取并转换为带有适当表头的Excel文件。

原始数据

0.050265,202241546530,50397417,0-127,128-255,1300812
0.051295,202245273937,65971821,0-127,128-255,1300812
0.050893,202248987612,65466246,0-127,128-255,1300812
0.050906,202252718742,65606097,0-127,128-255,1295785
0.050924,202256444380,65667670,0-127,128-255,1295785

对于上述数据,csvread()可以使用,但将数据放入多行,如下所示:
0.0502650000000000  202241546530.000    50397417    0   -127    128
-255    1300812 0   0   0   0
0.0512950000000000  202245273937.000    65971821    0   -127    128
-255    1300812 0   0   0   0
0.0508930000000000  202248987612.000    65466246    0   -127    128
-255    1300812 0   0   0   0
0.0509060000000000  202252718742.000    65606097    0   -127    128
-255    1295785 0   0   0   0
0.0509240000000000  202256444380.000    65667670    0   -127    128
-255    1295785 0   0   0   0

导入后期望的数据格式

        C1               C2            C3      C4     C5      C6
0.0502650000000000 202241546530.000 50397417 0-127 128-255 1300812
0.0512950000000000 202245273937.000 65971821 0-127 128-255 1300812
0.0508930000000000 202248987612.000 65466246 0-127 128-255 1300812
0.0509060000000000 202252718742.000 65606097 0-127 128-255 1295785
0.0509240000000000 202256444380.000 65667670 0-127 128-255 1295785

我可以处理如何添加特定的标头,但数据是分成多行的,我认为这是由于特殊字符-导致的。

请问有没有更好的方法将这些数据逐行读入Matlab?谢谢。


1
"该文件必须仅包含数字值。" 您正在导入除数字值之外的内容。 - beaker
你想将其作为表格导入吗?为什么您认为逐行读取更好?您想将数据的数字部分保留为数字数据,还是无所谓? - Sardar Usama
1个回答

3

这对我有效

clear

% Names of input and output files
file_in = 'sample_data.txt';
xl_filename = 'output.xlsx';

% Number of columns (assumed fixed)
n_col = 6;

fIN = fopen(file_in,'r');

% Load each line of the file as cell, split by ',', convert into a table
% entry and add it to the table
tline = fgets(fIN);
res_table = cell2table(cell(0,n_col));
while (ischar(tline))
    res_table = [res_table ; cell2table(strsplit(tline,','))];
    tline = fgets(fIN);
end

% Change table headers and write to the excel file
res_table.Properties.VariableNames = {'C1' 'C2' 'C3' 'C4' 'C5' 'C6'}
writetable(res_table,xl_filename,'Sheet',1,'Range','A1');

fclose(fIN);

这段代码逐行读取文件,将结果转化为单元数组并作为表格条目。由于以 ',' 分隔,'-' 保持不变。 writetable 将表格写入 Excel 电子表格,在 Sheet1 中从 A1 开始。你可以从不同的位置和工作表编号开始。该函数还有其他潜在有用的选项。

这种解决方案的缺点是需要显式地将电子表格转换为数字值,另一方面,这几乎是一个选择-一个点击的过程。直接在 MATLAB 中转换为数字并不容易,因为你的部分输入包含“-”符号。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接