Is there a simple way to condense the following codes?

3 views (last 30 days)
function greek=OptionGreeks(opt,arg1,arg2,arg3,arg4,arg5)
seed=rng;
if nargin==3
greek1=opt.opt1.OptionGreeks(arg1, arg2);
rng(seed);
greek2=opt.opt2.OptionGreeks(arg1, arg2);
elseif nargin==4
greek1=opt.opt1.OptionGreeks(arg1, arg2, arg3);
rng(seed);
greek2=opt.opt2.OptionGreeks(arg1, arg2, arg3);
elseif nargin==5
greek1=opt.opt1.OptionGreeks(arg1, arg2, arg3, arg4);
rng(seed);
greek2=opt.opt2.OptionGreeks(arg1, arg2, arg3, arg4);
else
greek1=opt.opt1.OptionGreeks(arg1, arg2, arg3, arg4, arg5);
rng(seed);
greek2=opt.opt2.OptionGreeks(arg1, arg2, arg3, arg4, arg5);
end
greek=greek1-greek2;
end
Above are my codes. opt is a SpreadOption class that has properties opt1 and opt2, which are Option class. Function SpreadOption.OptionGreeks() calls function Option.OptionGreeks() that accepts different number of input arguments.
I'm wondering if there's a way to condense the codes.
Also, I'm wondering what the easiest way is to customize my input argument, like opt.OptionPrice(S=3610, method='binomial tree', brunches=100000)? (just like python and R do)?It seems not convenient since MATLAB cannot overload/override a certain function.

Accepted Answer

OCDER
OCDER on 2 Aug 2018
function greek = OptionGreeks(opt, varargin)
if length(varargin) > 5; varargin = varargin(1:5); end
seed = rng;
greek1=opt.opt1.OptionGreeks(varargin{:});
rng(seed);
greek2=opt.opt2.OptionGreeks(varargin{:});
greek=greek1-greek2;
  4 Comments
Guixin Liu
Guixin Liu on 2 Aug 2018
I do not need 'varargout' for now, but I'm thinking about another question. In some other coding languages, I can write a function as
function OptionGreeks(S, greek_name, method='numerical', simTimes=1e6)
% function body
end
and I can call the function using syntax
OptionGreeks(102, 'delta', method='analytical')
or
OptionGreeks(102, 'delta', simTimes=1e7)
Note that they both have 3 input arguments. So I'm wondering whether there's a convenient way for Matlab to realize it.
I'd be grateful for any of your ideas.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Identification in Help Center and File Exchange

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!