Matlab function assumed inputs
Mostra commenti meno recenti
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.
Risposta accettata
Più risposte (3)
The simplest approach is to use the ARGUMENTS block:
pricingprogramme([],[])
pricingprogramme([],[],3,0.5)
function out = pricingprogramme(P,T,alpha,beta)
arguments
P
T
alpha = 10
beta = 0.1
end
out = alpha + beta;
end
Florian Bidaud
il 17 Nov 2023
Modificato: Florian Bidaud
il 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;
addOptional(p,'alpha',10, @isnumeric)
addOptional(p,'beta',0.1, @isnumeric)
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;
addParameter(p,'alpha',10, @isnumeric)
addParameter(p,'beta',0.1, @isnumeric)
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
1 Commento
Benjamin Wilson
il 17 Nov 2023
madhan ravi
il 17 Nov 2023
0 voti
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
1 Commento
Benjamin Wilson
il 17 Nov 2023
Categorie
Scopri di più su Argument Definitions in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!