Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous functions with varargin

I have a function that takes 3 mandatory inputs and 1 optional:

 f(A, B, C, X)

I want to use an anonymous function in this way

h = @(X)f(A,B,C,X)

where A, B, C have already been defined, so that I can just call h(1) and the code runs f(A,B,C,1), as well as h() to run f(A,B,C). The only way I am able to do it (correct me if I am wrong) is using varargin. I define

f(A,B,C,varargin)

and use

h = @(varargin)f(A,B,C,varargin)

The problem is that when I call directly f(A,B,C,1), then inside the function I have varargin = {1}. If I call h(1), then I have varargin = {{1}}. How can I avoid that? Is there a better way to implement what I want?

like image 869
Simon Avatar asked Nov 25 '25 18:11

Simon


1 Answers

You need to (or, rather, it may be best to) expand varargin into a comma-separated list with your current implementation:

h = @(varargin)f(A,B,C,varargin{:})

The question of if there is a better way is dependent on the specifics of the problem.

like image 64
TroyHaskin Avatar answered Nov 28 '25 07:11

TroyHaskin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!