Convert input of a function from scalar to vector

I am implementing Newton-Raphson method to find a zero.
I would like to convert this function:
F =@(x, y) x - y;
To that function:
F =@(X) X(1) - X(2);
Here I wrote it with x and y, but I have actually any amount of scalars (typically 800 or more). How do I automate the process?

2 Comments

Do you mean x and y are vectors containing 800 numbers?
A scalar is a vector of size 1x1, so you'd have to have 800 unique variables to have 800 scalars.
Yes, I meant x and y scalars, as I figured it to be my base case.
In my application I actually want to transform
F =@(x1, ..., x200, y1, ..., y200, z1, ..., z200, t1, ..., t200)
into
F =@(XY, ZT)
where both XY and ZT are 400x1 vectors (want column vectors for matrix multiplication)

Sign in to comment.

 Accepted Answer

A lot of the time, the easiest way to convert a function to accept vector inputs instead of individual inputs, is to use the Symbolic toolbox, and use matlabFunction() with the 'vars' option, and pass in a cell array of the variables to be grouped together. For example,
syms x y
F = x - y
F = 
fun = matlabFunction(F, 'vars', {[x, y]})
fun = function_handle with value:
@(in1)in1(:,1)-in1(:,2)

2 Comments

Thanks!
This was actually exactly what I wrote except for the {} wrapping the symbolic vetor in matlabFunction(). Did not spot it when I read the documentation.
The {} turns out to be important! And it is definitely easy to overlook or not understand the significance of it the first (numerous) times reading the matlabFunction documentation.

Sign in to comment.

More Answers (2)

Cris LaPierre
Cris LaPierre on 8 Feb 2022
Edited: Cris LaPierre on 8 Feb 2022
The main difference between the two functions you show is how the data is passed in.
F([x,y]) is the same as F(X) when X is a vector.

2 Comments

Yes, that is why I wrote it F(x,y), without [ ].
You need the [] to pass in x and y as a single input X.
F =@(X) X(1) - X(2);
x=5;
y=1;
F([x,y])
ans = 4

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!