2

I have an anonymous function with 10 variables now I want to evaluate it with data in a p=1x10 matrix like this:

answer=func(p(1),p(2),p(3),p(4),p(5),p(6),p(7),p(8),p(9),p(10))

i don't want to use this, i need something like:

answer=func(p(:))

but it generates error can anyone give me a solution?

1
  • Welcome to Stackoverflow! Please consider accepting the answer (green check mark on the left) to indicate the system that your problem is solved. Thank you! Commented Oct 22, 2015 at 6:10

1 Answer 1

4

You seem to have some basic misunderstandings using anonymous functions and its syntax.

For what I think you want to do, you basically have three options:

Option 1

Define the function with 10 input parameters and provide 10 input values - OR expand an input array as comma separated list using {:} which requires an intermediate num2cell step:

func1 = @(a,b,c,d,e,f,g,h,i,j) a + b + c + d + e + f + g + h + i + j
p = num2cell(p)
answer = func1(p{:})

Option 2

Define the function with 1 input parameters using an array with 10 values and provide this array:

func2 = @(p) p(1) + p(2) + p(3) + p(4) + p(5) + p(6) + p(7) + p(8) + p(9) + p(10)
answer = func2(p)

Option 3

The last option to use varargin is really case dependent and could look like:

func3 = @(varargin) [varargin{:}]
p = num2cell(p)
answer = func3(p{:})
Sign up to request clarification or add additional context in comments.

4 Comments

But p is not a cell array originally. You need num2cell first: pc = num2cell(p); answer = func1(pc{:})
@LuisMendo sure, gracias por el consejo ;) fixed!
@thewaywewalk Hahaha. ¡De nada! And +1 now
Or, alternatively, for a given fixed function func which OP has, you could define a front-end func_front=@(p) func(p(1),p(2),...,p(10)). At least this is how I interpret the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.