I have a file test.txt which I am reading the content from
the content is such as:
290729 123456
13984 654321
13272 111111
I have it until here:
inn = fgetl(thelist);
while ischar(inn)
disp(inn)
x = strsplit(inn);%I separate the to values in each line
toNum=x(1,1); %want to get first value and convert it to a number
theNum =double(cell2mat(toNum));%this does not work to convert {'290729'} to a number
class(theNum);%trying to find out what is the type after I tried to make a number out of it
inn = fgetl(thelist);
end
I need to convert this value (such as 290729 or 13984 in this case to a number)

 채택된 답변

Konrad
Konrad 2021년 9월 23일
편집: Konrad 2021년 9월 23일

1 개 추천

Hi Nicle
you need str2double() (or str2num()), not double().
double() gives you the UTF(?) code corresponding to the input string. Eg:
double('a') % = 97 or
ans = 97
double('1') % = 49
ans = 49
Conversely:
char([97 49]) % = 'a1'
ans = 'a1'
But:
str2double('1') % = 1
ans = 1
Also str2double() works on cellstrings, no need to for cell2mat():
str2double({'1' '2'}) % = 1 2
ans = 1×2
1 2
Best, Konrad

댓글 수: 3

Nicle Davidson
Nicle Davidson 2021년 9월 23일
I tried str2num and str2double, I get an error such as:
290729 123456
Error using str2num (line 37)
Input must be a character vector or string scalar.
Konrad
Konrad 2021년 9월 23일
Then you allready converted the string to a number (note that for str2num() the input cannot be a cellstring).
Also consider Chunrus answer if your text file exclusively contains numbers as indicated in your question and if you don't need to read the file line-by-line. Then simply using load(filename,'-ascii') might also be a solution.
Nicle Davidson
Nicle Davidson 2021년 9월 23일
Yes, and thank you for both answers! It helped

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Chunru
Chunru 2021년 9월 23일

2 개 추천

You can use "readmatrix" function:
% Generate the data file
a = [290729 123456
13984 654321
13272 111111];
writematrix(a, 'test.txt', 'Delimiter', ' ')
type test.txt
290729 123456 13984 654321 13272 111111
% Read the .txt file
b = readmatrix('test.txt')
b = 3×2
290729 123456 13984 654321 13272 111111

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

질문:

2021년 9월 23일

댓글:

2021년 9월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by