MATLAB有一个函数/运算符可以指示变量的类型吗(类似于JavaScript中的typeof
运算符)?
使用class
函数:
>> b = 2
b =
2
>> a = 'Hi'
a =
Hi
>> class(b)
ans =
double
>> class(a)
ans =
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
字段。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
>>
if ( string(class(b)) == 'double' ) fprintf(1, 'b is double'); end
翻译为中文: - khaverim