How to Import/parse sparse data from a text file into MATLAB?
Show older comments
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
Accepted Answer
More Answers (1)
Walter Roberson
on 21 Sep 2020
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 Comments
Walter Roberson
on 21 Sep 2020
filename = 'test.txt';
opt = detectImportOptions(filename, 'FileType', 'fixedwidth');
opt.ExtraColumnsRule = 'ignore';
opt.SelectedVariableNames = {'Var2', 'Var3'};
opt.DataLines = [3 inf];
data = readtable(filename, opt);
data = rmmissing(data);
Now data.Var1 will contain the Name field and data.Var2 will contain the corresponding numeric value.
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
