Convert input of a function from scalar to vector

62 views (last 30 days)
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
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.
Lukas-Marie Jean Stanislas Gamard
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

Walter Roberson
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
F = 
fun = matlabFunction(F, 'vars', {[x, y]})
fun = function_handle with value:
@(in1)in1(:,1)-in1(:,2)
  2 Comments
Lukas-Marie Jean Stanislas Gamard
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.
Walter Roberson
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.

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
Cris LaPierre
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])
ans = 4

Sign in to comment.


Ashwini
Ashwini on 6 Jun 2023
F =@(X) X(1) - X(2); x=5; y=1; F([x,y])

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!