【问题标题】:Use a property of a classdef in another .m file?在另一个 .m 文件中使用 classdef 的属性?
【发布时间】:2011-03-07 04:11:04
【问题描述】:

这是我的代码:

f.m:

classdef f < handle
    properties (Access = public)
        functionString = '';
        x;
    end
    methods
        function obj = f
            if nargin == 0
                syms s;
                obj.x = input('Enter your function: ');
                obj.functionString = ilaplace(obj.x);
            end
        end
        function value = subsref(obj, a)
            t = a.subs{:};
            value = eval(obj.functionString);
        end
        function display(obj)
        end
    end
end

test.m:

syms s t;
[n d] = numden(f.x); % Here I want to use x, which is the user input, How can I do such thing?
zeros = solve(n);
poles = solve(d);
disp('The Poles:');
disp(poles);
disp('The Zeros:');
disp(zeros);
disp('The Result:');
disp(z(t));
disp('The Initial Value:');
disp(z(0));
disp('The Final Value:');
disp(z(Inf));

当我在命令窗口中输入 test 时,它会告诉我以下信息:

>> test
??? The property 'x' in class 'f' must be accessed from a class instance because it
is not a Constant property.

【问题讨论】:

  • 就像上面说的,你需要先创建对象f,然后写一个访问器方法返回x的值。
  • @Alex 如何定义访问器方法?我应该在哪里创建对象 f,在 test.m 中?最后一件事,那怎么调用方法呢?

标签: matlab matlab-class


【解决方案1】:

正如 Alex 指出的那样,您需要一个 f 的实例来访问成员属性 x,如下所示:

myf = f();
f.x

您不需要访问器方法来获取x,因为它被定义为公共属性。如果您选择将 x 设为私有,那么您需要一个类似这样的访问器方法:

function x = getX( obj )
  x = obj.x;
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 2012-03-24
    • 2019-08-20
    相关资源
    最近更新 更多