フィルターのクリア

Object Oriented Programming - Leaving properties from objects empty.

4 ビュー (過去 30 日間)
BdS
BdS 2018 年 8 月 28 日
コメント済み: Adam 2018 年 8 月 29 日
Hi everybody! I am writing the following code:
classdef Value0_1
properties
Price
Earnings
ddd
BookValue
P_E_Calc
P_B_Calc
end
methods
function PE=Value0_1(price,earnings,Ddd)
if nargin <2
PE.Price=price;
PE.Earnings=earnings;
PE.ddd=Ddd;
end
end
end
end
Now, I would like to create an object by typing in the command Window PriceEarnings=Value0.1(555,555,~). the following error comes: Error: Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters.
--> How can I leave the argument Ddd empty?

採用された回答

Matt J
Matt J 2018 年 8 月 28 日
編集済み: Matt J 2018 年 8 月 28 日
The call should look like PriceEarnings=Value0_1(555,555) and the code for the constructor should look like,
function PE=Value0_1(price,earnings,Ddd)
if nargin >=1
PE.Price=price;
end
if nargin>=2
PE.Earnings=earnings;
end
if nargin>=3
PE.ddd=Ddd;
end
end
  4 件のコメント
Matt J
Matt J 2018 年 8 月 28 日
編集済み: Matt J 2018 年 8 月 28 日
You might also think about using inputParser, to make all the parameters non-positional.
Adam
Adam 2018 年 8 月 28 日
I tend to use
if exist( 'earnings', 'var' ) && ~isempty( earnings )
validateattributeS( earnings,... )
else
earnings = someDefaultValue;
end
nowadays rather than using nargin, for this purpose. Then I pass in empty, like Matt J has done which causes it to use the default value I supply. I occasionally use the inputParser, but I've generally only done it when I allow 'name', 'value' pairs of any of my properties to be set like in many Matlab functions.

サインインしてコメントする。

その他の回答 (1 件)

BdS
BdS 2018 年 8 月 29 日
Thanks a lot Adam and Matt. I am quite new in OOP. Therefore I would like the following question. In my project the objects (=stock factors) have different properties depending on which factor you choose. The classes corresponds to Styles (=families of stock factors). This means that everytime when I create a factor, some properties stay empty (without values) which I really do not know if this is common? Do you know a better method of solving this task with matlab?
  1 件のコメント
Adam
Adam 2018 年 8 月 29 日
It's hard to know without more specific examples, but you can create class hierarchies where a derived class will extend the base class, which sounds like what you may want, for the extra properties that may be empty in some objects otherwise. Obviously if every property is different then you would just want two independent classes, but I am assuming there is commonality too.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by