How to read text file with float and string types into matrix
조회 수: 11 (최근 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!