MATLAB Answers

How can I convert all string cells in a table to numerical values?

1 view (last 30 days)
Ted Baker
Ted Baker on 6 Jan 2020
Answered: Stijn Haenen on 6 Jan 2020
Hi I'm trying to import a text file into a table format. The text file is separated by single spaces, which I have included as an attachment. However, several columns have the data wrapped in a quote mark - why is this and what can I do to remove them? My matlab code looks as follows:
filename = 'test.txt';
T = readtable(filename,'Delimiter',' ','ReadVariableNames',false);
T([1],:) = [];
size(T);
EDIT: I see now the quote marks represent a string in the cell, but how can I convert all the strings to numerical values?

  0 Comments

Sign in to comment.

Accepted Answer

Stijn Haenen
Stijn Haenen on 6 Jan 2020
If you use the import data tool, you can chose to ouput the data in matrix instead of a table.
With this tool you can also generate a script to import your data:
opts = delimitedTextImportOptions("NumVariables", 9);
% Specify range and delimiter
opts.DataLines = [7, Inf];
opts.Delimiter = " ";
% Specify column names and types
opts.VariableNames = ["Agilent", "TechnologiesE8362BMY43020256A060432", "VarName3", "VarName4", "VarName5", "VarName6", "VarName7", "VarName8", "VarName9"];
opts.VariableTypes = ["double", "double", "double", "double", "double", "double", "double", "double", "double"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
opts.ConsecutiveDelimitersRule = "join";
opts.LeadingDelimitersRule = "ignore";
% Import the data
test = readtable("D:\thuis\test.txt", opts);
%% Convert to output type
test = table2array(test);
%% Clear temporary variables
clear opts

  0 Comments

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags