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"," ")

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by