Problem with *txt File Format conversion using Matlab
1 view (last 30 days)
Show older comments
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.
0 Comments
Answers (2)
ANKUR KUMAR
on 18 Mar 2021
Edited: ANKUR KUMAR
on 18 Mar 2021
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)
You can get the dlmcell from file exchange.
0 Comments
Cris LaPierre
on 18 Mar 2021
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"," ")
[h,m,s]=hms(d.Var1);
d.Var1 = duration(h,m,round(s))
writetable(d,"roundData.txt","WriteVariableNames",false,"Delimiter"," ")
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!