我的目标是使用MATLAB OOP设计在MATLAB中编程的可重用引擎。这是我第一次尝试这样做。我要解决的问题如下:我有一个抽象类cPayoffBase,它为未知类型的收益定义了接口。继承cPayoffBase,我有一个实现调用选项的具体类cPayoffCall。现在,我定义了另一个类cVanillaDerivs,它接受用户定义的收益对象和执行价格。当我将用户定义的对象传递给cVanillaDerivs以计算一些数量时,Index exceeds matrix dimensions.就会出现异常。我将详细提供代码。

cPayoffBase.m

classdef (Abstract) cPayoffBase < handle

    methods (Abstract)
        mfGetPayoff(argSpotPrc)
    end

end


cPayoffCall.m

classdef cPayoffCall < cPayoffBase

    properties (GetAccess = private, SetAccess = private)

        dmStrikePrc

    end

    methods

    function obj = cPayoffCall(argStrikePrc)

        obj.dmStrikePrc = argStrikePrc;

    end

    function rslt = mfGetPayoff(obj, argSpotPrc)

        rslt = max(argSpotPrc - obj.dmStrikePrc, 0.0);

    end

end


cVanillaDerivs.m

classdef cVanillaDerivs

%% Data Members
properties (GetAccess = private, SetAccess = private)
    dmPayoffObj
    dmExpiryDt
end

%% Implementation
methods

    % Constructor
    function obj = cVanillaDerivs(argPayoffObj, argExpiryDt)

        obj.dmPayoffObj = argPayoffObj;
        obj.dmExpiryDt  = argExpiryDt;

    end

    % Member Functions
    function rslt = mfGetExpriyDt(obj)

        rslt = obj.dmExpiryDt;

    end

    function rslt = mfGetDerivPayoff(argSpotPrc)

        rslt = obj.dmPayoffObj(argSpotPrc);

    end
end
end


命令窗口

>> clear classes
>> spot = 100; strike = 50; T = 1;
>> payoffObj = cPayoffCall(strike);
>> typeVanilla = cVanillaDerivs(payoffObj, T);
>> mfGetDerivPayoff(typeVanilla, spot)
Index exceeds matrix dimensions.

Error in cVanillaDerivs/mfGetDerivPayoff (line 37)
            rslt = obj.dmPayoffObj(argSpotPrc);


在C ++中,假设我有一个包装器类并包装了类对象cPayoffBase,则可以为类return (*dmPayoff)(dmSpotPrc)中的双返回函数mfGetDerivPayoff(double dmSpotPrc) const做类似cVanillaDerivs的操作。请让我知道我的错误,如果可能的话,如何在MATLAB OOP中像C ++一样实现相同的过程。

最佳答案

您正在尝试访问属性dmPayoffObj的元素编号100。但是,此属性设置为payOffObj,这不是数组。因此错误。

我想您想要的是返回dmPayoffObj的收益。您应该按如下所示更改类mfGetDerivPayoff的方法cVanillaDerivs

function rslt = mfGetDerivPayoff(argSpotPrc)
    rslt = obj.dmPayoffObj.mfGetPayoff(argSpotPrc);
end

10-07 13:27