Inconsisent(?) behaviour of str2num() with a particular usage
4 ビュー (過去 30 日間)
古いコメントを表示
The task in hand for me was to generate an empty array corresponding to the class/datatype of the input.
%Example 1
input = 'string';
output = char.empty
%Example 2
input = single(rand);
output = single.empty
My approach to this was to obtain the class of the input and use it with str2num -
input1 = "MATLAB";
str1 = sprintf('%s.empty', class(input1));
out1 = str2num(str1)
class(out1)
As you can see above, that the output is an empty array of double class and not of string class (as expected by me). This also occurs with char data-type
input2 = 'Batman'
str2 = sprintf('%s.empty', class(input2));
out2 = str2num(str2)
class(out2)
I have checked for these datatypes - single, double, all integer classes, figure, datetime, duration, calendarDuration, timeseries, string and char. It works for all the datatyes except for the last two.
I expected the code to work for all classes.
My questions are - Did I expect wrongly?
If not, why does this give incorrect (edit - different) output for 2 data types?
4 件のコメント
Stephen23
2023 年 5 月 22 日
"I should have done a better job at going through the documentation."
Both DGM and I were referring to the code itself, not the documentation. Try this:
type str2num
採用された回答
VBBV
2023 年 5 月 21 日
編集済み: VBBV
2023 年 5 月 21 日
The function str2num can be used to convert the strings that inherently contain numbers to double class.
In your case there are no numbers in the outputs from sprintf function. Therefore, it results in empty [] which belongs to double class by default.
The reason why it worked for other data types is that they all belong to or contain numbers except for char & string
Hope this clarifies
6 件のコメント
VBBV
2023 年 5 月 21 日
@Dyuman Joshi, Figure and datetime inherits Number property and are considered or treated as numeric by Matlab, If you read the documentation of figure it is clearly stated.
figure(n) finds a figure in which the Number property is equal to n, and makes it the current figure. If no figure exists with that property value, MATLAB® creates a new figure and sets its Number property to n.
Hope this clarifies
その他の回答 (1 件)
Steven Lord
2023 年 5 月 22 日
If you want to evaluate the Static empty method of your class, don't use eval or str2num. Use feval or str2func.
classname = "string";
result = feval(classname + ".empty", 2, 0)
f = str2func(classname + ".empty");
result = f(0, 5)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!