在Matlab中动态创建类 [英] Creating classes dynamically in matlab

查看:94
本文介绍了在Matlab中动态创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个结构,有没有一种方法可以在MATLAB中创建类?举个例子

Given a structure, is there a way to create a class in MATLAB? Take for instance

>> p = struct(); p.x = 0; p.y = 0;
>> p

p = 

    x: 0
    y: 0

>> name = 'Point'

name =

Point

我想做的是,给了一个包含类名的字符串和一个结构,该结构包含了我想创建一个类的字段,而不必编写一个显式编写定义的文件.

What I would like to do, is given a string containing the name of the class and a struct with containing the fields I would like to create a class without having to write a file explicitly writing the definition.

现在,如果我们使用class(p),我们将获得struct.我想做的是创建一个Point类型的对象,这样当我执行class(obj)时,就会得到Point.

Right now if we use class(p) we will obtain struct. What I want to do is create an object of the type Point so that when I do class(obj) then I get Point.

除了在MATLAB中编写带有类定义的文件然后执行它以外,还有什么想法可以实现?

Any ideas how to accomplish this besides writing a file in MATLAB with the class definition and then executing it?

推荐答案

要么您有与Point类相关的特定功能(方法),要么与Line类,在这种情况下,无论如何您应该手动写出这些类,或者可以创建一个具有动态创建属性的单个dynamicprops类,除非您确实需要调用名为class的方法,您只需调用classname即可大大简化生活.

Either you have specific functionality (methods) associated with the Point class as opposed to e.g. the Line class, in which case you should write out the classes by hand, anyway, or you can make a single dynamicprops class that can have dynamically created properties, and unless you really need to call a method named class, you much simplify your life by calling classname instead.

classdef myDynamicClass < dynamicprops
properties (Hidden)
myClass %# this stores the class name
end
methods
function obj = myDynamicClass(myClassName,varargin)
%# synopsis: obj = myDynamicClass(myClassName,propertyName,propertyValue,...)
%# myClassName is the name of the class that is returned by 'classname(obj)'
%# propertyName/propertyValue define the dynamic properties

obj.myClass = myClassName;

for i=1:2:length(varargin)
addprop(obj,varargin{i})
obj.(varargin{i}) = varargin{i+1};
end
end

function out = classname(obj)
out = obj.myClass;
end

end 
end

这篇关于在Matlab中动态创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆