How to read text file with float and string types into matrix
9 次查看(过去 30 天)
显示 更早的评论
Hello,
I have a text file with different value types such as string and float. Is there any automatic function to read the file into matrix?
Text file for example:
26/08/2020 08:25:30 $GPS_ABC 100 E 200 M
26/08/2020 08:25:31 $GPS_ABC 101 E 210 M
26/08/2020 08:25:32 $GPS_ABC 102 E 220 M
The only solution i found is:
while ~feof(text_file)
file_data{i}=textscan(text_file,'%f %f %f %f %f %f %s %f %s %f %s',1,'delimiter',['/',':'],'headerlines',1);
i=i+1;
end
Thanks
0 个评论
回答(1 个)
Serhii Tetora
2020-8-26
%% Import data from text file
% Script for importing data from the following text file:
%
% Auto-generated by MATLAB on 26-Aug-2020 14:12:55
%% Setup the Import Options and import the data
opts = delimitedTextImportOptions("NumVariables", 11);
% Specify range and delimiter
opts.DataLines = [1, Inf];
opts.Delimiter = [" ", "/", ":"];
% Specify column names and types
opts.VariableNames = ["VarName1", "VarName2", "VarName3", "VarName4", "VarName5", "VarName6", "VarName7", "VarName8", "VarName9", "VarName10", "VarName11"];
opts.VariableTypes = ["double", "double", "double", "double", "double", "double", "string", "double", "string", "double", "string"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
opts.ConsecutiveDelimitersRule = "join";
% Specify variable properties
opts = setvaropts(opts, ["VarName7", "VarName9", "VarName11"], "WhitespaceRule", "preserve");
opts = setvaropts(opts, ["VarName7", "VarName9", "VarName11"], "EmptyFieldRule", "auto");
% Import the data
text = readtable("text.txt", opts);
%% Clear temporary variables
clear opts
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!