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?
CodePudding user response:
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);