How to set a default value for my custom function
154 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Yode
el 17 de Jul. de 2017
Respondida: Lee
el 11 de Feb. de 2023
I hope to create such custom function
function addnum(mat,n=numel(mat))
mat+n
I mean I try to add a number into the element of mtrix mat,but if I don't give a explicit value for n,I hope the n will be the number of the mtrix self.
0 comentarios
Respuesta aceptada
Stephen23
el 17 de Jul. de 2017
Editada: Stephen23
el 17 de Jul. de 2017
Unfortunately MATLAB does not (currently) allow defining default values in the function definition line itself (nor does it allow arguments to be specified by name, only by position). To define a default value you can use the input parser class (I find this slow and pointlessly complex), or simply use nargin like this:
function out = addnum(mat,n)
if nargin<2
n = 3;
end
out = mat+n;
end
For more multiple optional arguments you should consider using a structure or name-value pairs: see my FEX submission num2words for an example of this.
0 comentarios
Más respuestas (2)
Lee
el 11 de Feb. de 2023
This is the way to define default number in matlab
function addnum(mat,n)
arguments
mat
n=numel(mat)
end
mat+n
end
Be sure to list all arguments in order
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!