# Matlab function assumed inputs

9 views (last 30 days)
Benjamin Wilson on 17 Nov 2023
Edited: Stephen23 on 17 Nov 2023
Does Matlab support functions with inputs that if not given, can be assumed?
I would like to write some code similar to the following - where if alpha and beta are not given when calling the function they are assigned to a set value 10 and -0.1 respectively
function [x,y] = pricingprogramme(P,T,alpha = 10, beta = -0.1)
... some code using P,T aswell as alpha and beta ....
end
Any help would be greatly appreciated.

Dyuman Joshi on 17 Nov 2023
Yes, use varargin with nargin -
[x1,y1] = pricingprogramme(5,10)
x1 = 16
y1 = 40.1000
[x2,y2] = pricingprogramme(1,2,3,4)
x2 = -9
y2 = -5
function [x,y] = pricingprogramme(P,T, varargin)
if nargin == 4
alpha = varargin{1};
beta = varargin{2};
elseif nargin==2
alpha = 10;
beta = -0.1;
else
%Modify other cases as per need
error('Number of inputs must be 2 or 4')
end
%Random definitions
x = P + T - alpha*beta;
y = P*T - (alpha + beta);
end
Benjamin Wilson on 17 Nov 2023
Thank you! Very helpul!

Stephen23 on 17 Nov 2023
Edited: Stephen23 on 17 Nov 2023
The simplest approach is to use the ARGUMENTS block:
pricingprogramme([],[])
ans = 10.1000
pricingprogramme([],[],3,0.5)
ans = 3.5000
function out = pricingprogramme(P,T,alpha,beta)
arguments
P
T
alpha = 10
beta = 0.1
end
out = alpha + beta;
end

Florian Bidaud on 17 Nov 2023
Edited: Florian Bidaud on 17 Nov 2023
Hi,
if you want positional arguments, use addOptional with an inputParser like this :
% to use the function as
% [x,y] = pricingprogramme(P, T, alpha_value, beta_value)
% or pricingprogramme(P, T, alpha_value)
% or pricingprogramme(P, T)
function [x,y] = pricingprogramme(P,T,varargin)
p = inputParser;
parse(p,varargin{:})
alpha = p.Results.alpha;
beta = p.Results.beta;
... some code using P,T aswell as alpha and beta ....
end
If you want to add them as parameters, use addParameter like this :
% to use the function as
% [x,y] = pricingprogramme(P, T, alpha=alpha_value, beta=beta_value)
% or pricingprogramme(P, T, alpha=alpha_value)
% or pricingprogramme(P, T, beta=beta_value)
% or pricingprogramme(P, T, beta=beta_value, alpha=alpha_value)
% or pricingprogramme(P, T)
function [x,y] = pricingprogramme(P,T,varargin)
p = inputParser;
parse(p,varargin{:})
alpha = p.Results.alpha;
beta = p.Results.beta;
... some code using P,T aswell as alpha and beta ....
end
NOTE: @isnumeric is to check that the input value is a numeric value
Benjamin Wilson on 17 Nov 2023
Thank you!

madhan ravi on 17 Nov 2023
Use nargin() to determine if number of inputs are less than three assign the default values to alpha and beta else feed in the actual values of them
Benjamin Wilson on 17 Nov 2023
Thank you!

### Categories

Find more on Argument Definitions in Help Center and File Exchange

R2023b

### Community Treasure Hunt

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

Start Hunting!