How to turn text into numbers

1 view (last 30 days)
Daulton Gray
Daulton Gray on 20 Oct 2021
Edited: DGM on 21 Oct 2021
So if I have a .txt file and all it has is two lines. One line is x=5 and the other line y=0. I used importdata(filename) to import it but now I have a 2x1 array with {'x=5'} and {'y=0'}. How do I turn those into x=5 and y=0 numerical values?

Accepted Answer

DGM on 21 Oct 2021
Edited: DGM on 21 Oct 2021
Well I'm sure there are more robust ways, but if all the file ever has is those two lines in that specific order with that specific formatting, then
C = importdata('blah.txt');
C = str2double(regexprep(C,'(x|y)=',''));
%C = str2double(strrep(strrep(C,'x=',''),'y=','')); % or alternatively
%C = str2double(cellfun(@(x) x(3:end),C,'uniform',false)); % or super-simple
x = C(1)
x = 5.1234
y = C(2)
y = 0.1230
Or if you wanted to actually look for numbers that follow 'x=' and 'y=', you could do
C = importdata('blah.txt');
C = regexp(C,'(?<=^(x|y)=)\d+[,|.]?\d*','match');
x = str2double(C{1})
x = 5.1234
y = str2double(C{2})
y = 0.1230
You could be more specific if you wanted, explicitly looking for the number after 'x=' and assigning that to x, etc
C = importdata('blah.txt');
x = regexp(C,'(?<=^x=)\d+[,|.]?\d*','match');
x = str2double(vertcat(x{:}))
x = 5.1234
y = regexp(C,'(?<=^y=)\d+[,|.]?\d*','match');
y = str2double(vertcat(y{:}))
y = 0.1230
In this case, the order of the lines doesn't matter. It will also return all matches; i.e. if the file contains multiple lines starting with 'x=', all the numbers will be returned in a numeric array. Of the given examples, this would be the safer way to do things, but by no means am I claiming that there's nothing better. There are probably canonical ways of doing this sort of thing that I've never used.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by