0

Assume I have a vector A=[a1 a2 a3 ... an], and a defined function handle f=@(x1,x2,x3,..,xn), how can I input the vector to the function handle without explicitly writing f(A(1),A(2),...,A(n))? The code I am writing gives me different n for different situations, and it is not practical to manually input the function parameters because it is of variable size.

Example: I might get f=@(x,y)(x^2+y^2) and A=[1 2], I can say f(A(1),A(2)) and my problem is solved, but only if I have two variables. If I have f=@(x,y,z)(x^2+y^2+z^2) and A=[1 2 3], I should write f(A(1),A(2),A(3)).

This may be rephrased probably as how can I control the number of the "slots" in the function handle the way I want?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
HousamKak
  • 23
  • 3
  • Wolfie's answer solves your immediate problem, but you should really consider writing functions to take arrays as input. MATLAB is a vectorized language, it should not be used with lots of individual numbers, but with one or a few arrays of numbers. Your examples here are likely not the functions you are actually dealing with, but for example, `f=@(x,y,z)(x^2+y^2+z^2)` is the same as `f=@(v)sum(v.^2)`, except that the latter works for vectors of any length. – Cris Luengo Oct 15 '21 at 15:58

1 Answers1

2

You can go via a cell array

% Convert input array to a cell
A = num2cell( A );
% Deal the cell array to the inputs of f
f( A{:} );

Or you just write your function so that it indexes an array, rather than relying on multiple scalars, i.e. f=@(x,y)x+y; becomes f=@(z)z(1)+z(2);

Wolfie
  • 27,562
  • 7
  • 28
  • 55