How to Import/parse sparse data from a text file into MATLAB?
4 次查看(过去 30 天)
显示 更早的评论
I've been having issues with parsing data into MATLAB from a text file. The textfile has discontinuities between its strings (it has spaces), and it seems like everytime I tried to import the data into matlab it just combines everything and messes up the data. I would like to basically read the text file (attached) and import the corresponging strings with their values into an array (probably).
I also tried to import the file into Excel and see if I could delimiter my data in a nicer format so I can easily import it into MATLAB but excel also does not like the data format and it breaks every word into a column which messes up everything as well.
Any help would be greatly appreciate it.
Here is what I did so far:
%% Setup the Import Options and import the data
opts = delimitedTextImportOptions("NumVariables", 3);
% Specify range and delimiter
opts.DataLines = [2, Inf];
opts.Delimiter = ",";
% Specify column names and types
opts.VariableNames = ["TITLE", "BEGININPUTDATAECHO", "VarName3"];
opts.VariableTypes = ["string", "string", "string"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
% Specify variable properties
opts = setvaropts(opts, ["TITLE", "BEGININPUTDATAECHO", "VarName3"], "WhitespaceRule", "preserve");
opts = setvaropts(opts, ["TITLE", "BEGININPUTDATAECHO", "VarName3"], "EmptyFieldRule", "auto");
% Import the data
ATR42500zjf2 = readtable("test.txt", opts);
%% Clear temporary variables
clear opts
0 个评论
采纳的回答
Mohammad Sami
2020-9-20
After some testing, it seems your file can be read by setting delimiter to 3x spaces.
You can combine this with the rest of your options here as needed.
opts = detectImportOptions('test.txt','Delimiter',' ','ConsecutiveDelimitersRule','join','ExpectedNumVariables',3,'LeadingDelimitersRule','ignore');
opts = setvartype(opts,'VALUEDIMENSIONS','char');
a = readtable('test.txt',opts);
8 个评论
Mohammad Sami
2020-9-22
I think the only other option left is to used fixed width option. This assumes that each column has fixed character width.
opts = fixedWidthImportOptions('NumVariables',4,'VariableWidths',[30 12 6 12]);
opts.VariableNames = {'DESCRIPTION' 'NAME' 'VALUE' 'DIMENSIONS'};
a = readtable('test.txt',opts);
b = readtable('test2.txt',opts);
更多回答(1 个)
Walter Roberson
2020-9-21
S=fileread('test.txt') ;
data = str2double(regexp(S, '-?\d+(\.\d*)?, 'match' ) ;
This code allows for negative data even though the sample file does not have any.
This code allows for integers with no decimal point. The file has one of those.
This code does not allow for numbers less than 1 that do not have a leading 0 - 0.1 is fine but not .1 without the 0
This code does not allow exponential notation.
4 个评论
另请参阅
类别
在 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!