如何在Matlab中使对象在其类中可访问?

时间:2016-12-09 20:46:20

标签: matlab oop subclass

在本课程中,如何让fig个对象在其班级中拥有自己的相关属性,例如my_function;

classdef Test
    properties
        a
        b
    end

    methods
        function obj = Test(a, b)
            obj.a = a;
            obj.b = b;
        end  
        function [] = my_function(obj)
            fig.Name   %%% here fig object is needed
            disp('done!')
        end  
        function [fig] = my_figure(obj) 
            fig = figure();
        end
    end
end

1 个答案:

答案 0 :(得分:1)

您需要将fig存储为您班级的属性,然后在my_function内,您将能够访问当前实例的fig属性。作为旁注,如果您希望能够通过引用传递您的类实例,那么您将要创建MATLAB的handle类的子类:

classdef Test < handle
    properties
        fig         % Setup a property to hold the handle to the figure
        a
        b  
    end

    methods
        function obj = Test(a, b)
            obj.a = a;
            obj.b = b;
        end  

        function [] = my_function(obj)
            % Access and modify the figure handle as needed
            obj.fig.Name = 'Name';
            disp('done!')
        end  

        function [fig] = my_figure(obj) 
            fig = figure();

            % Store the handle in the "fig" property of the class
            obj.fig = fig;
        end
    end
end