Passing individual elements of an array into a function

144 views (last 30 days)
Say I have a function 'myfun' that takes n inputs: i.e. myfun(x1, x2, ... xn).
I have an array 'arr' that has n elements: i.e. arr = [ y1, y2, ... yn ].
I want to pass in y1, y2 ... yn as the input to myfun without typing myfun( arr(1), arr(2), ... arr(n) ). Is there a compact way of doing this?
If I type in myfun( arr(1:end) ) for example, x1 = arr and x2 ... xn are left unassigned,
but I want x1 = arr(1) = y1, x2 = arr(2) = y2 ... xn = arr(n) = yn.

Answers (2)

Walter Roberson
Walter Roberson on 26 Jan 2021
temp = num2cell(arr(1:end));
This situation is most common when the user has used matlabFunction to convert a symbolic function into a function handle. There is a completely different solution for that situation that avoids doing the splitting at all.
x = sym('x', [1 n]);
myfun = matlabFunction(YourSymbolicExpression, 'vars', {x});
This will tell matlabFunction to expect all of the input values to be packed into a single parameter, and to extract them from there as needed.
In this particular way of writing it, if the function is vectorizable, then the result will be vectorized with each column representing a different input. For example,
x = sym('x', [1 2]);
y = x(1)^2 + x(2);
myfun = matlabFunction(y, 'vars', {x});
would produce
myfun = @(in) in(:,1).^2 + in(:,2)
and you could
myfun([1 2; 3 4])
which would result in
[1^2+2; 3^2+4]
If you used 'vars', {x.'} then each row would correspond to a different variable and it would vectorize along the columns.

Matt Gaidica
Matt Gaidica on 26 Jan 2021
I don't think so, closest I can think of is using varargin. I think many people are going to ask why you need to use your design instead of passing a matrix itself into the function.
  1 Comment
Walter Roberson
Walter Roberson on 26 Jan 2021
varargin will not help, not unless you code like
function myfun(varargin)
if nargin == 1
values = nargin{1};
values = [nargin{:}];
to allow you to pass either a single argument matrix or a list of values.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!