0

How do you include two named functions, which are not nested, in one anonymous function?

For example, say I have a file mainFunction.m which contains

function varargout = mainFunction(in1) % in1 is always a cell %% based on what in1 is, output a function using usefulFunction1UsuallyAFile() varargout{1}=@(x)usefulFunction1UsuallyAFile(in1{1},x); %% something else that I'd like to make into the anonymous function %if numel(in1)>1 % mainFunction(in1{2:end}); %end % I need the call of mainFunction(in1{2:end}) to be preferably always grouped with the call of varargout{1} %% main body of mainFunction() % abbreviated: doing something with varargout{1}(...) (one time) %%%% end function out = usefulFunction1UsuallyAFile(in1,in2) out ={in1,in2}; end 

My current solution is instead of

varargout{1}=@(x)usefulFunction1UsuallyAFile(in1,x); 

I do

varargout{1}=@(x){usefulFunction1UsuallyAFile(in1{1},x),... mainFunction(in1{2:end})}; 

And in the caller of mainFunction() and the user of its output, I unwrap the output; as well as handling empty in1 in mainFunction() specifically.

But there are quite a bit of restrictions that come with this solution. For one, I have to modify all the callers of mainFunction() in the case of updating an existing library of functions.

And then, only the output of mainFunction(in1{1}) can be accessed by its caller.

And then there are other restrictions with this structure.

Is there a less restrictive method that maybe uses a more general syntax or function that can combine two functions into 1 anonymous function?

2
  • not really an answer, but maybe this functional programming approach (code) will help? AFAIK using if statements inside anonymous functions isn't nice. you could consider using the ternary operator in that repo? Commented Aug 19 at 4:31
  • I really do not understand what you are trying to accomplish. You want to return a handle to usefulFunction1UsuallyAFile(), which takes two arguments, but give it a fixed series of values for the first argument. Later, calling this function with some value, you want the function called with each of the values in the fixed series and the new value. So handle(x) should run usefulFunction1UsuallyAFile(in1{1},x), usefulFunction1UsuallyAFile(in1{2},x), usefulFunction1UsuallyAFile(in1{3},x), etc. Is that right? If so, did you think of using cellfun? Commented Oct 8 at 20:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.