str2num is returning and empty matrix: []
이전 댓글 표시
Problem:
I'm trying to convert a string containing a number into a double, but the output of str2num keeps giving me an empty matrix [].
Context:
I've imported data from an excel sheet with importdata(). That data comes in as a cell array. To extract data from a specific cell, I use cell2mat(). This yeilds numbers in the class: Char. (Example: '5'). I use convertCharsToString('5') to convert that character into a string. What I'm left with is ans = "5".
Now, I want to convert this "5" into a double. So, I used str2num(ans), and I get [] as the output (instead of 5 of class double).

I even tried this debugg:
a = "5";
strcmp(a,month)
and got a logical = 0...
Any ideas why this isn't woking?
댓글 수: 2
"So, I used str2num(ans)"
Ugh, so you are relying on unreliable ANS ...
Take a look at your workspace, and see what ANS really is:

What makes you think that the text 'string' should be able to be converted into a number?
Solution: forget about ANS. Use a proper variable.
"I've imported data from an excel sheet with importdata()"
Forget about unreliable IMPORTDATA. Import the data properly using e.g. READTABLE... which also lets you import those timestamps as DATETIME objects and then access their YEAR, MONTH, etc properties. Much better than all of that fiddly buggy messing around with text that you are doing.
Please upload your data file by clicking the paperclip button.
You don't need to use cell2mat; just use curly braces to get the contents of a cell in a cell array.
For example:
datetempDat = {'5/8/2024 0:00,20.87';'5/8/2024 0:02,20.87'}
dat1 = datetempDat{1}
채택된 답변
추가 답변 (1개)
Since month is a string containing the text representation of a number, you don't need to use str2num. Just call double on it.
month = "5"
d = double(month)
This can even handle some extra spaces
month2 = " 5 "
double(month2)
카테고리
도움말 센터 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!