【发布时间】:2010-10-09 09:00:55
【问题描述】:
MATLAB 是否具有指示变量类型的函数/运算符(类似于 JavaScript 中的 typeof 运算符)?
【问题讨论】:
MATLAB 是否具有指示变量类型的函数/运算符(类似于 JavaScript 中的 typeof 运算符)?
【问题讨论】:
【讨论】:
使用class函数:
>> b = 2
b =
2
>> a = 'Hi'
a =
Hi
>> class(b)
ans =
double
>> class(a)
ans =
char
【讨论】:
if ( string(class(b)) == 'double' ) fprintf(1, 'b is double'); end
class 方法以返回任何随机字符串。
class() 与 Javascript 的 typeof 运算符完全一样。
要获取有关变量的更多详细信息,您可以使用 whos 命令或 whos() 函数。
这是在 MATLAB R2017a 的命令行窗口上执行的示例代码。
>> % Define a number
>> num = 67
num =
67
>> % Get type of variable num
>> class(num)
ans =
'double'
>> % Define character vector
>> myName = 'Rishikesh Agrawani'
myName =
'Rishikesh Agrwani'
>> % Check type of myName
>> class(myName)
ans =
'char'
>> % Define a cell array
>> cellArr = {'This ', 'is ', 'a ', 'big chance to learn ', 'MATLAB.'}; % Cell array
>>
>> class(cellArr)
ans =
'cell'
>> % Get more details including type
>> whos num
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos myName
Name Size Bytes Class Attributes
myName 1x17 34 char
>> whos cellArr
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> % Another way to use whos i.e using whos(char_vector)
>> whos('cellArr')
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> whos('num')
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos('myName')
Name Size Bytes Class Attributes
myName 1x17 34 char
>>
【讨论】:
由于没有人提到它,MATLAB 也有 metaclass 函数,它返回一个对象,其中包含有关传入实体的各种信息。这些meta.class 对象可用于继承测试(通过常见的比较运算符)。
例如:
>> metaclass(magic(1))
ans =
class with properties:
Name: 'double'
Description: ''
DetailedDescription: ''
Hidden: 0
Sealed: 0
Abstract: 0
Enumeration: 0
ConstructOnLoad: 0
HandleCompatible: 0
InferiorClasses: {0×1 cell}
ContainingPackage: [0×0 meta.package]
RestrictsSubclassing: 0
PropertyList: [0×1 meta.property]
MethodList: [272×1 meta.method]
EventList: [0×1 meta.event]
EnumerationMemberList: [0×1 meta.EnumeratedValue]
SuperclassList: [0×1 meta.class]
>> ?containers.Map <= ?handle
ans =
logical
1
我们可以看到class(someObj)等价于metaclass(someObj)结果的Name字段。
【讨论】: