我有一个枚举类型,就像这样:
classdef(Enumeration) bla_type < int32
enumeration
bla_one(1)
bla_2(2)
end
end
我可以通过以下方式获取'元素的字符串表示':
char(bla_type.bla_one)
=>
bla_one
很遗憾,Matlab Coder 对此不太支持。有没有其他替代方案?
我有一个枚举类型,就像这样:
classdef(Enumeration) bla_type < int32
enumeration
bla_one(1)
bla_2(2)
end
end
char(bla_type.bla_one)
=>
bla_one
classdef someenum < int32 %#codegen
enumeration
First_thing (0)
Second_thing (2)
Another_thing (3)
No_thing (4000)
end
end
我们接下来还有一个构建时函数叫做'buildsomeenum2name.m':
function [namearray, memberidx] = buildsomeenum2name
%BUILDSOMEENUM2NAME Compile-time creation of lookup table for someenum
% THIS FUNCTION IS NOT CODER COMPATIBLE, BUT IS CALLED DURING COMPILE
% TO CREATE A LOOKUP TABLE.
[members, names]=enumeration('someenum');
maxlen = 0;
for i=1:numel(names)
maxlen = max(maxlen, numel(names{i}));
end
namearray = char(zeros(numel(names), maxlen));
for i=1:numel(names)
namearray(i, 1:numel(names{i})) = names{i};
end
memberidx = int32(members); %#ok<NASGU>
end
buildsomeenum2name
函数时,它将创建一个字符串数组,其中包含枚举类型的所有成员名称,并创建另一个向量列表,其中包含相同顺序的数值。function name = someenum2name(enum) %#codegen
%SOMEENUM2NAME Get the string name of an enumerated type
% The following line loads namearray and memberidx with constant arrays
coder.extrinsic('buildsomeenum2name');
[namearray, memberidx] = coder.const(@buildsomeenum2name);
% First find the index of the enumerated type in the memberidx vector
index = find(memberidx==int32(enum));
if isempty(index)
name = 'UNKNOWN';
return;
end
name = deblank(namearray(index,:));
end
coder.const
命令在编译时评估buildsomeenum2name
并创建查找表。我们必须指示Coder不要尝试编译buildsomeenum2name
,因此使用coder.extrinsic
命令告诉它忽略该函数。然后someenum2name
可以查找字符串的索引并将其提取出来(使用deblank是因为数组中的字符串有尾随的0需要被去除)。函数someenum2name
可以在MATLAB和Coder编译代码中调用。>> someenum2name(someenum.No_thing)
ans =
No_thing
尝试[~,s]=enumeration('bla_type')
。您将获得一个字符串的单元数组,其中包含s
中元素的名称。所以bla_one
将在s {1}
中。不知道MATLAB编码器是否支持此功能。