AndrewV
AndrewV

Reputation: 13

Using vector as inputs to anonymous function in MATLAB

Lets say I have an anonymous function with n inputs, f(x1, x2 x3,... xn) and a vector of length n, lets say vector = [1, 2, 3,... n]. Is there a way to get MATLAB to take the individual values of the vector as the corresponding inputs of f? For example:

f = @(x,y,z) x+y+z;
vector = [1,2,3];
f(vector)
ans = 
       6

I want to use this in a larger script file, where I won't know the number of inputs there are, but instead the program will work it out as it goes based on the length(vector).

For clarification, the code above emulates what I would like to happen. If you put that right into MATLAB, you get:

Not enough input arguments.

Upvotes: 1

Views: 719

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112759

Convert the vector to a cell array using num2cell, and from that generate a comma-separated list:

>> f = @(x,y,z) x+y+z;
>> vector = [1,2,3];
>> cell_array = num2cell(vector);
>> f(cell_array{:})
ans =
     6

Upvotes: 2

Related Questions