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

조회 수: 11 (최근 30일)
Guy Cohen
Guy Cohen 2020년 8월 26일
댓글: Guy Cohen 2020년 8월 27일
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

답변 (1개)

Serhii Tetora
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
  댓글 수: 1
Guy Cohen
Guy Cohen 2020년 8월 27일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by