3

我正在编写我的第一个 MATLAB OO 应用程序,我对组合、聚合和关系的一般实现感到困惑。

我的问题是:如何在matlab中实现聚合或关联一对多?我可以在哪里举一些例子?

此外,我正在使用 ArgoUml 来设计我的应用程序,是否有任何插件可以在 matlab 中自动生成代码?

提前致谢

4

2 回答 2

2

这是一个类关联的简单示例。该场景包含一门可以招收许多学生的课程:

学生.m

classdef Student < handle
    properties
        name
    end
    methods
        function obj = Student(name)
            if nargin > 0
                obj.name = name;
            end
        end
        function delete(obj)
            fprintf('-- Student Destructor: %s\n',obj.name);
        end
    end
end

课程.m

classdef Course < handle
    properties
        name        %# course name
        std         %# cell array of students
    end
    properties(Access = private)
        lastIdx = 1;
    end
    methods
        function obj = Course(name, capacity)
            obj.name = name;
            obj.std = cell(capacity,1);
        end
        function addStudent(obj, std)
            if obj.lastIdx > numel(obj.std)
                fprintf(2, 'Sorry, class is full\n');
                return
            end
            obj.std{obj.lastIdx} = std;
            obj.lastIdx = obj.lastIdx + 1;
        end
        function printClassRoster(obj)
            fprintf('Course Name = %s\n', obj.name);
            fprintf('Enrolled = %d, Capacity = %d\n', ...
                obj.lastIdx-1, length(obj.std));
            for i=1:obj.lastIdx-1
                fprintf('ID = %d, Name = %s\n', i, obj.std{i}.name);
            end
        end
    end

end

这是测试上述类的代码:

c = Course('CS101', 3);
for i=1:4
    name = sprintf('amro%d',i);
    fprintf('Adding student: %s\n', name)
    c.addStudent( Student(name) )
end

fprintf('\nClass Roster:\n=============\n')
c.printClassRoster()

fprintf('\nCleaning up:\n')
clear c

输出:

Adding student: amro1
Adding student: amro2
Adding student: amro3
Adding student: amro4
Sorry, class is full
-- Student Destructor: amro4

Class Roster:
=============
Course Name = CS101
Enrolled = 3, Capacity = 3
ID = 1, Name = amro1
ID = 2, Name = amro2
ID = 3, Name = amro3

Cleaning up:
-- Student Destructor: amro1
-- Student Destructor: amro2
-- Student Destructor: amro3
于 2012-06-13T16:24:35.773 回答
1

您可以查看MATLAB 中的 Object-Oriented Programming ,并在文档中参阅Object-Oriented Programming

我建议仔细看看Value or Handle Class — which to Use 。简而言之,句柄类允许您传递引用,而值类始终是原始对象的副本。

我会惊讶地发现 ArgoUml 的插件,因为 MATLAB 主要由工程师使用,而不是软件开发人员。

于 2012-06-12T11:05:51.003 回答