Convert input of a function from scalar to vector
62 views (last 30 days)
Show older comments
Lukas-Marie Jean Stanislas Gamard
on 8 Feb 2022
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
Cris LaPierre
on 8 Feb 2022
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.
Accepted Answer
Walter Roberson
on 8 Feb 2022
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
fun = matlabFunction(F, 'vars', {[x, y]})
2 Comments
Walter Roberson
on 9 Feb 2022
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.
More Answers (2)
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
Cris LaPierre
on 9 Feb 2022
Edited: Cris LaPierre
on 9 Feb 2022
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])
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!