How to turn text into numbers
2 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
DGM
2021 年 10 月 21 日
編集済み: DGM
2021 年 10 月 21 日
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)
y = C(2)
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})
y = str2double(C{2})
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{:}))
y = regexp(C,'(?<=^y=)\d+[,|.]?\d*','match');
y = str2double(vertcat(y{:}))
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.
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Naming Conventions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!