[英]read text delimited file and write to excel in matlab
我有以下格式的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
然后繼續(有1016行)。 我想將其轉換為excel文件。 我嘗試了以下
fileID = fopen('test_datum.txt');
C = textscan(fileID,'%s %f32 %f32 %d8 %s');
但是它將數據插入1016X5單元中。 我想稍后再將此單元格寫入excel文件。
謝謝
textscan
函數有時可能很難處理。 數據格式很難定義,並且傾向於將數據填充到單元格向量中(將結果重新排序為單個單元格矩陣有點煩人)。 我建議您改用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'
如果您的Matlab版本大於或等於R2016b
,則可以先前在該文件上運行detectImportOptions函數 。 掃描結果可以根據您的需要進行調整(您可以更改變量名稱,變量類型,缺少值的默認值等):
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'
最重要的是,表格真的很容易導出到Excel文件。 您要做的就是使用具有適當設置的writetable函數 。
這是一種更簡便的替代方法,可讓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.