Is it possible to have function handles with optional arguments in Matlab
Show older comments
I have about 25-50 Matlab function handles saved in a cell array so I can evaluate each of them using a for loop. Those function handles were converted from symbolic expression.
However, some of the function handles need 4 arguments, other need 2 arguments and few do not need any argument (they are constants). For example, some them need (x1,x2,y1,y2) as the arguments, some need(x1,x2), some need (y1,y2) and few need nothing.
My question: is it possible to have function handles with optional arguments in Matlab? which means I can give 4 arguments to the all function handles and let them decide if they need all or not. If they don't need some of them, they can just simply ignore them.
Thank you.
2 Comments
Wan Ji
on 12 Aug 2021
New syntax appears in matlab 2021a, it may help solve your problem!
Walter Roberson
on 12 Aug 2021
No that does not solve the problem. The = form converts to name/value option pairs.
Accepted Answer
More Answers (2)
Image Analyst
on 12 Aug 2021
Edited: Image Analyst
on 12 Aug 2021
0 votes
It's certainly possible with a regular function. See varargin and nargin in the help. Can you use a regular function? You can still get a handle to a regular function just like you can with an anonymous function.
For an anonymous function, I don't know. I don't think it's possible. If you want to do it for a regular, normal function, let me know.
1 Comment
Muhammad Imron
on 12 Aug 2021
With anonymous function, you can take in the argument in workspace instead of function arguments.
a = 1; b = 2; c = 1;
f = @(x) a*x.^2 + b*x + c;
y = f(2) % one function arguments; a b c are in workspace
1 Comment
Image Analyst
on 12 Aug 2021
I think what he was thinking regarding optional arguments is for you to not pass them in or specify them, and for those variables to take on default values that the function author decided upon in advance.
a = 1; b = 2;
f = @(x, c) a*x.^2 + b*x + c;
% Call without specifying c and having it use some default value for c.
% Case 1: arguments a & b are in workspace. Use (for example) 9 for c instead of 1.
y = f(2) % Won't work - c not specified
But like you pointed out, the way to do that is to just specify the value you want for c in advance:
% Case 2: arguments a, b, & c are in workspace. Use 1 for c since that is what we specified.
c = 1;
y = f(2, c) % Works since the "default" arguments a, b, and c are in the workspace.
% or even declare f() with no c at all and don't pass in anything.
f = @(x) a*x.^2 + b*x + c; % Use c value from workspace.
y = f(2)
Or of course you could just use a normal function instead of an anonymous one (which is what I'd do).
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!