How to read text file with float and string types into matrix

21 views (last 30 days)
Guy Cohen
Guy Cohen on 26 Aug 2020
Commented: Guy Cohen on 27 Aug 2020
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

Answers (1)

Serhii Tetora
Serhii Tetora on 26 Aug 2020
%% 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
  1 Comment
Guy Cohen
Guy Cohen on 27 Aug 2020
Thank you Serhii,
I'm looking for code that get the variables only by delimiter, that means without declaring its types before (e.g. %f, %s, "double", "string")
I don't know if such function exists but it will help a lot

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!