如何创建enums类型在MATLAB

如题所述

1. 你可以得到与新型MATLAB的类的函数:
classdef (Sealed) Colors
properties (Constant)
RED = 1;
GREEN = 2;
BLUE = 3;
end
methods (Access = private) % private so that you cant instantiate
function out = Colors
end
end
end

这是不是一个真正的类型,但由于MATLAB是弱类型,如果整数,你可以做的事情,它近似:
line1 = Colors.RED;
...
if Colors.BLUE == line1
end

在这种情况下,MATLAB“enums”是接近C样式enums-为整数代替语法。
随着你甚至可以使MATLAB的enums接近阿达在复杂,但不幸的是与awk的语法。
2.
从R2010b中开始 CodeGo.net,MATLAB支持
从示例
classdef Colors
properties
R = 0;
G = 0;
B = 0;
end
methods
function c = Colors(r, g, b)
c.R = r; c.G = g; c.B = b;
end
end
enumeration
Red (1, 0, 0)
Green (0, 1, 0)
Blue (0, 0, 1)
end
end

3.
你可以从你的Matlab代码Java的enums类。定义它们在Java中,并把它们放在你的Matlab的javaclasspath。
// Java class definition
package test;
public enum ColorEnum {
RED, GREEN, BLUE
}

您可以在M-代码中引用它们通过。
mycolor = test.ColorEnum.RED
if mycolor == test.ColorEnum.RED
disp('got red');
else
disp('got other color');
end
% Use ordinal() to get a primitive you can use in a switch statement
switch mycolor.ordinal
case test.ColorEnum.BLUE.ordinal
disp('blue');
otherwise
disp(sprintf('other color: %s', char(mycolor.toString())))
end

它不会对其他类型的,虽然。字符串有一个奇怪的回报大小。
>> test.ColorEnum.RED == 'GREEN'
ans =
0
>> test.ColorEnum.RED == 'RED'
ans =
1 1 1

4.
如果你想要做类似于马克建议,您可以直接使用一个结构来表示你的类型,而不是一个全新的类:
colors = struct('RED',1,'GREEN',2,'BLUE',3);

一个好处是,你可以轻松地访问结构两种不同的方式。您可以指定一个域的域
a = colors.RED;

或者你充满活力的领域,如果你有一个字符串字段:
a = colors.('RED');

事实上,有几个好处,做什么马克建议,创造一个全新的类来表示一个“enums”对象:
您可以控制如何在对象被修改。
你可以把定义在一个地方,它在多个地方。
您可以控制的失败,使他们更“优雅”,像返回一个空矩阵,如果你试图访问一个不存在的字段(而不是抛出一个错误)。
但是,如果你不需要那种,只是需要做的快,结构很可能是最简单,最直接的它也将与旧版本的MATLAB的工作,唐“最新的OOP
5.
其实是在MATLAB R2009b关键字叫做'。这似乎是,我不能说我知道是怎么回事,但函数却可能存在。
你可以找到它在matlabroot\toolbox\distcomp\examples\+examplesclassdef(Enumeration) DmatFileMode < int32
enumeration
ReadMode(0)
ReadCompatibilityMode(1)
WriteMode(2)
end
<snip>
end

6.
你可以做一个matlab的类,它的行为就像一个Java的老类型安全enums模式。马克的解决方案的修改可以把它从C样式的类型定义,更像是Java样式的类型安全enums。在这个版本中,常量的值类型颜色的对象。
有利的一面:
该类型可以进行检查(在由==等操作,以防止对生的或其他类型的enums。
你可以明确地检查你的变量的类型(在
值显示与可读性,而不是不透明的代码。
操作和std()不就enums意义是不允许的。
缺点:
较长的类定义。但是,这是所有的样板,并且可以用于任何其他enums类,只需改变类和常量属性。
这些enums在switch块不能直接。需要弹出的代码了,失去了类型安全。
对象会比原语慢。相关的,如果你在循环中的常量。
整体来说,我不知道哪种方式更好。避风港“无论是在实践中。
classdef (Sealed) Color
%COLOR Example of Java-style typesafe enum for Matlab
properties (Constant)
RED = Color(1, 'RED');
GREEN = Color(2, 'GREEN');
BLUE = Color(3, 'BLUE');
end
properties (SetAccess=private)
% All these properties are immutable.
Code;
Name;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods (Access = private)
%private so that you can't instatiate directly
function out = Color(InCode, InName)
out.Code = InCode;
out.Name = InName;
end
end
methods (Static = true)
function needa(obj)
%NEEDA Asserts that obj must be a Color
if ~isa(obj, mfilename)
error('Input must be a %s; got a %s', mfilename, class(obj));
end
end
end
methods (Access = public)
function display(obj)
disp([inputname(1) ' =']);
disp(obj);
end
function disp(obj)
if isscalar(obj)
disp(sprintf('%s: %s (%d)', class(obj), obj.Name, obj.Code));
else
disp(sprintf('%s array: size %s', class(obj), mat2str(size(obj))));
end
end
function out = eq(a, b)
%EQ Basic "type-safe" eq
check_type_safety(a, b);
out = [a.Code] == [b.Code];
end
function [tf,loc] = ismember(a, b)
check_type_safety(a, b);
[tf,loc] = ismember([a.Code], [b.Code]);
end
function check_type_safety(varargin)
%CHECK_TYPE_SAFETY Check that all inputs are of this enum type
for i = 1:nargin
if ~isa(varargin{i}, mfilename)
error('Non-typesafe comparison of %s vs. %s', mfilename, class(varargin{i}));
end
end
end
end
end

这里有一个函数来行使它。
function do_stuff_with_color(c)
%DO_STUFF_WITH_COLOR Demo use of the Color typesafe enum
Color.needa(c); % Make sure input was a color
if (c == Color.BLUE)
disp('color was blue');
else
disp('color was not blue');
end
% To work with switch statements, you have to explicitly pop the code out
switch c.Code
case Color.BLUE.Code
disp('blue');
otherwise
disp(sprintf('some other color: %s', c.Name));
end

例子
>> Color.RED == Color.RED
ans =
1
>> Color.RED == 1
??? Error using ==> Color>Color.check_type_safety at 55
Non-typesafe comparison of Color vs. double
Error in ==> Color>Color.eq at 44
check_type_safety(a, b);
>> do_stuff_with_color(Color.BLUE)
color was blue
blue
>> do_stuff_with_color(Color.GREEN)
color was not blue
some other color: GREEN
>> do_stuff_with_color(1+1) % oops - passing the wrong type, should error
??? Error using ==> Color>Color.needa at 26
Input must be a Color; got a double
Error in ==> do_stuff_with_color at 4
Color.needa(c); % Make sure input was a color
>>

A小调怪癖的两种方法:把常数上的“==”,以防止不良左手的C约定不帮助尽可能多的在这里。在Matlab中,如果你“=”用这个常数,而不是一个错误在LHS,但只需要建立一个新的局部结构变量的颜色,它会掩盖enums类。
>> Colors.BLUE = 42
Colors =
BLUE: 42
>> Color.BLUE = 42
Color =
BLUE: 42
>> Color.RED
??? Reference to non-existent field 'RED'.

7.
在尝试了这个页面上的其他建议,我降落在安德鲁的完全面向对象的方法。很不错的-感谢安德鲁。

万一有人有兴趣,不过,我做了(我认为是)特别是,我删除了需要双击指定的enums对象。在现在是反思和系统。此外,式()和函数进行了重新编写,以回
馈为enums对象的矩阵妥善形的返回值。最后,check_type_safety()函数进行了修改,使与包的目录(例如,
似乎很好地工作,但知道你在想什么:
classdef (Sealed) Color
%COLOR Example of Java-style typesafe enum for Matlab
properties (Constant)
RED = Color(1);
GREEN = Color(2);
BLUE = Color(3);
end
methods (Access = private) % private so that you can''t instatiate directly
function out = Color(InCode)
out.Code = InCode;
end
end

% ============================================================================
% Everything from here down is completely boilerplate - no need to change anything.
% ============================================================================
properties (SetAccess=private) % All these properties are immutable.
Code;
end
properties (Dependent, SetAccess=private)
Name;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods
function out = eq(a, b) %EQ Basic "type-safe" eq
check_type_safety(a, b);
out = reshape([a.Code],size(a)) == reshape([b.Code],size(b));
end
function [tf,loc] = ismember(a, b)
check_type_safety(a, b);
[tf,loc] = ismember(reshape([a.Code],size(a)), [b.Code]);
end
function check_type_safety(varargin) %CHECK_TYPE_SAFETY Check that all inputs are of this enum type
theClass = class(varargin{1});
for ii = 2:nargin
if ~isa(varargin{ii}, theClass)
error('Non-typesafe comparison of %s vs. %s', theClass, class(varargin{ii}));
end
end
end
% Display stuff:
function display(obj)
disp([inputname(1) ' =']);
disp(obj);
end
function disp(obj)
if isscalar(obj)
fprintf('%s: %s (%d)\n', class(obj), obj.Name, obj.Code);
else
fprintf('%s array: size %s\n', class(obj), mat2str(size(obj)));
end
end
function name=get.Name(obj)
mc=metaclass(obj);
mp=mc.Properties;
for ii=1:length(mp)
if (mp{ii}.Constant && isequal(obj.(mp{ii}.Name).Code,obj.Code))
name = mp{ii}.Name;
return;
end;
end;
error('Unable to find a %s value of %d',class(obj),obj.Code);
end;
end
end

谢谢,
石匠
8.
如果您可以访问统计工具箱,你可能一个明确的对象。
9.
Toys = {'Buzz', 'Woody', 'Rex', 'Hamm'};
Toys{3}
ans = 'Rex'

10.
如果你需要的类型只是传递到C#或.NET程序集,
您可以构建并通过使用MATLAB 2010enums:
A = NET.addAssembly(MyName.dll)
% suppose you have enum called "MyAlerts" in your assembly
myvar = MyName.MyAlerts.('value_1');

您也可以检查MathWorks公司正式在答案
怎么做的。在MATLAB 7.8 NET的值(R2009a)?

// the enum "MyAlerts" in c# will look something like this
public enum MyAlerts
{
value_1 = 0,
value_2 = 1,
MyAlerts_Count = 2,
}
温馨提示:答案为网友推荐,仅供参考