# When defining an anonymous function, how do I utilize cell indexing of an intermediate function?

4 views (last 30 days)
Aditya Desai on 21 Mar 2023
Commented: Aditya Desai on 27 Mar 2023
I have an anonymous function called "epsin" (shown below) which puts its inputs into another, intermediate, anonymous function, called "epsTarray". This "epsin" function is then in turn used in other functions which are then in turn used in optimization fits (using lsqnonlin). My difficulty here is extracting the data within the first cell of the epsTarray function, as it returns a 2x1 cell, and then taking the specific (1,1,:) set within that extracted cell. MATLAB says that this may be invalid syntax and I run into the error "Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters."
Is there a way to make this work, or a way around this problem?
epsin = @(n)(epsTarray(n(1),n(2),n(3),n(4),n(5),n(6),n(7),n(8),n(9),n(10))){1}(1,1,:);
Some more clarity: epsTarray takes in 10 inputs and returns a 2x1 cell of a 3x3x(variable number) double array. epsin is intended to be an array which takes the extracted numbers from the first cell and (1,1,:) places of epsTarray.
VBBV on 21 Mar 2023
Moved: VBBV on 22 Mar 2023
Try something like below
epsTarray = @(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10) ... expression
y = epsTarray(n(1),n(2),n(3),n(4),n(5),n(6),n(7),n(8),n(9),n(10));
epsin = @(n) y{1}(1,1,:)
instead of direct access of data through anonymous function, assign it to an intermediate variable y and then access its contents.

Matt J on 21 Mar 2023
Edited: Matt J on 21 Mar 2023
Here's one way. Ultimately, though, it probably makes more sense to be using non-anonymous functions.
epsin=@(n) wrapper(n, epsTarray);
function out=wrapper(n, hfun)
tmp=hfun(n(1),n(2),n(3),n(4),n(5),n(6),n(7),n(8),n(9),n(10));
out=tmp{1}(1,1,:);
end
Aditya Desai on 27 Mar 2023
I got this to work after some minor modifications (reshaping the out array). Thank you!

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2022b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!