[英]read text delimited file and write to excel in matlab
I have a txt file in this format: 我有以下格式的txt文件:
Right,28772.163,39356.163,1,Speaker1 sp,39356.163,49499.163,99,Speaker1 sp,129129.21,147210.21,99,Speaker2 Next step is,147210.21,160881.21,1,Speaker2 surgery's,160881.21,181608.21,1,Speaker2
and it goes on (it has 1016 rows). 然后继续(有1016行)。 I would like to convert it into excel file. 我想将其转换为excel文件。 I tried the following 我尝试了以下
fileID = fopen('test_datum.txt');
C = textscan(fileID,'%s %f32 %f32 %d8 %s');
But it inserts the data into a 1016X5 cell. 但是它将数据插入1016X5单元中。 I would like later to write this cell into an excel file. 我想稍后再将此单元格写入excel文件。
thank you 谢谢
The textscan
function can sometimes be tricky to deal with. textscan
函数有时可能很难处理。 The data format is hard to define and it tends to cram data into a cell vector (reordering the result into a single cell matrix is kinda annoying). 数据格式很难定义,并且倾向于将数据填充到单元格向量中(将结果重新排序为单个单元格矩阵有点烦人)。 What I suggest you is to use the readtable function instead: 我建议您改用readtable函数 :
T = readtable('data.txt')
Var1 Var2 Var3 Var4 Var5
______________ _________ _________ ____ __________
'Right' 28772.163 39356.163 1 'Speaker1'
'sp' 39356.163 49499.163 99 'Speaker1'
'sp' 129129.21 147210.21 99 'Speaker2'
'Next step is' 147210.21 160881.21 1 'Speaker2'
'surgery's' 160881.21 181608.21 1 'Speaker2'
If you have a Matlab release greater than or equal to R2016b
, you can previously run the detectImportOptions function on the file. 如果您的Matlab版本大于或等于R2016b
,则可以先前在该文件上运行detectImportOptions函数 。 The result of the scan can be tweaked according to your needs (you can change the variable names, variable types, default for missing values, etc...): 扫描结果可以根据您的需要进行调整(您可以更改变量名称,变量类型,缺少值的默认值等):
opts = detectImportOptions('data.txt');
% the previous values where char, double, double, double, char
opts.VariableTypes = {'char' 'single' 'single' 'int8' 'char'};
% alternatively, this can be used:
% opts = setvartype(opts,{'char' 'single' 'single' 'int8' 'char'})
T = readtable('data.txt',opts)
Var1 Var2 Var3 Var4 Var5
______________ ________ ________ ____ __________
'Right' 28772.16 39356.16 1 'Speaker1'
'sp' 39356.16 49499.16 99 'Speaker1'
'sp' 129129.2 147210.2 99 'Speaker2'
'Next step is' 147210.2 160881.2 1 'Speaker2'
'surgery's' 160881.2 181608.2 1 'Speaker2'
On the top of that, tables are really easy to export to Excel files. 最重要的是,表格真的很容易导出到Excel文件。 All you have to do is to use the writetable function with the appropriate settings. 您要做的就是使用具有适当设置的writetable函数 。
Here's an alternate, easier approach that lets MATLAB functions automatically take care of more of the data processing: 这是一种更简便的替代方法,可让MATLAB函数自动处理更多数据处理:
% read the file into a table
T = readtable('test_datum.txt');
% convert the table to a cell array
C = table2cell(T);
% write the cell array to an Excel file
xlswrite('output.xlsx', C);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.