Array Indexing and Function Handling question.

2 views (last 30 days)
Hello,
My question revolves around creating functions with multiple equations (components) and calculating stuff with them.
F = @(x,y) [3*x+y.^2 , x.^2+3*x-1]; %F1 is the first component, F2 is the second
PointXY = [0 0];
z = F(PointXY) %this part doesn't work, but every other method I can think of is suboptimal
My project includes calculating an estimate of a Jacobian matrix of F. My main question is:
How can I calculate Z without having to write:
z = F(PointXY(1), PointXY(2));
This does work, but this also assumes that the programmer knows how many variables the function has! If the function has any other numbers of variables (ex: 3 in (x,y,z)), this program would not work at all. Is there a easy fix to this, or do I have to create another entire function just to calculate the image of a single point?

Accepted Answer

Star Strider
Star Strider on 20 Oct 2021
It would be necessary to define ‘F’ in terms of a single parameter vector —
F = @(xy) [3*xy(1)+xy(2).^2 , xy(1).^2+3*xy(1)-1]; %F1 is the first component, F2 is the second
PointXY = [0 0];
z = F(PointXY)
z = 1×2
0 -1
So what was previously ‘x’ is now ‘xy(1)’, and ‘y’ is now ‘xy(2)’. This is the only way I know of to get it to work with one vector argument.
.
  3 Comments
Steven Lord
Steven Lord on 20 Oct 2021
If you can't or don't want to modify your original function you could write an adapter for users of the function.
F = @(x,y) [3*x+y.^2 , x.^2+3*x-1]; %F1 is the first component, F2 is the second
PointXY = [0 0];
g = @(xy) F(xy(1), xy(2));
z = g(PointXY)
z = 1×2
0 -1

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!