Problem with *txt File Format conversion using Matlab

1 回表示 (過去 30 日間)
Dung Tran
Dung Tran 2021 年 3 月 18 日
コメント済み: Dung Tran 2021 年 3 月 19 日
Hi everyone, I have a question.
I want to re-write a format *txt into another format *txt.
Here is an example (1):
12:20:30.12345 1111 1112 1113 1114 1115 1116 1117 1118 1119 2000
I want to convert it into (2):
12:20:30 1111 1112 1113 1114 1115 1116 1117 1118
How can I read the file (1) and then convert it into the format as (2) .
NOTE: 12:20:30.12345 mean the time with second detail. 12hr 20 mins and 30.12345 second. I want the second to be rounded, example : 30.4s will 30s and 30.6s is 31s
The file with 11 columns and row is about over 5000 lines
Thank you very much.

回答 (2 件)

ANKUR KUMAR
ANKUR KUMAR 2021 年 3 月 18 日
編集済み: ANKUR KUMAR 2021 年 3 月 18 日
I have used a sample file just like yours (attached). Hope it helps.
clc
clear
formatSpec = '%14s%5s%5s%5s%5s%5s%5s%5s%5s%5s%s%[^\n\r]';
fileID = fopen('sample_file.txt','r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', '', 'WhiteSpace', '', 'ReturnOnError', false);
dataArray{1} = strtrim(dataArray{1});
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
raw(1:length(dataArray{col}),col) = dataArray{col};
end
for kk=1:size(raw,1)
first_col=round(str2double(raw{kk}(7:end)),1)
output{kk}=[num2str(first_col) raw(2:end)]
end
output_var=cat(1,output{:});
dlmcell('sample_ouput.txt',output_var)

Cris LaPierre
Cris LaPierre 2021 年 3 月 18 日
I would use readtable to load your text file. In newer releases, this will automatically read in the first column as a duration.
Use the hms function to extract the time components, and use round to round your seconds, assigning the result back into the table.
Once complete, use writetable to create a new text file.
d=readtable("rawData.txt","ReadVariableNames",false,"Delimiter"," ")
d = 1×11 table
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10 Var11 _______________ ____ ____ ____ ____ ____ ____ ____ ____ _____ _____ 12:20:30.123450 1111 1112 1113 1114 1115 1116 1117 1118 1119 2000
[h,m,s]=hms(d.Var1);
d.Var1 = duration(h,m,round(s))
d = 1×11 table
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10 Var11 ________ ____ ____ ____ ____ ____ ____ ____ ____ _____ _____ 12:20:30 1111 1112 1113 1114 1115 1116 1117 1118 1119 2000
writetable(d,"roundData.txt","WriteVariableNames",false,"Delimiter"," ")
  1 件のコメント
Dung Tran
Dung Tran 2021 年 3 月 19 日
thank u very much, thats works!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by