using fsolve when the function handle takes in 2 variables that are both vectors
43 views (last 30 days)
Show older comments
I'm trying to solve system of non-linear equations. My function handle fun takes in 2 variables ( x and y) that are both vectors.Each vector has 2 components. I want fsolve to return me 2 vectors with 2 components each. However, fsolve can only return one vector. How do I find an appropriate solution for my problem? Any help appreciated.
fun=@(x,y) [exp(-exp(-(x+y))) - x.*(1+x.^2); x.*cos(y) + y.*sin(x) - [0.5;0.5]];
x0=[1;1]; % initial guess for x vector
y0=[0;1]; % initial guess for y vector
[result1,result2]=fsolve(fun,x0,y0);
0 Comments
Accepted Answer
dpb
on 19 Apr 2020
Recast as 4-vector w/ v(1:2) -- x; v(3:4) -- y:
fun2=@(x) [exp(-exp(-(x(1:2)+x(3:4)))) - x(1:2).*(1+x(1:2).^2); ...
x(1:2).*cos(x(3:4)) + x(3:4).*sin(x(1:2)) - [0.5;0.5]];
>> fsolve(fun2,[x0;,y0])
Equation solved.
fsolve completed because the vector of function values is near zero
as measured by the value of the function tolerance, and
the problem appears regular as measured by the gradient.
<stopping criteria details>
ans =
0.4627
0.4627
0.0876
0.0876
>> fun2(ans)
ans =
1.0e-11 *
-0.2900
-0.0679
-0.7623
-0.0910
>>
3 Comments
mary
on 3 Oct 2021
@dpb could you please answer this question: https://nl.mathworks.com/matlabcentral/answers/1464779-solve-a-set-of-two-linear-equations
It's very similar to this one. With the differnce that I want to keep f1 and f2 as they are. And for the sake of clarity, I dont want to concatenate x and y into a vector.
John D'Errico
on 3 Oct 2021
@mary - what you want to do, and what you CAN do are very different things. We can't always get what we want. A fellow named Mick eloquently told us that many years ago.
Optimizers are not set up to optimize functions where the parameters are scattered among the inputs. Surely you understand that cannot happen. So even if the variables of interest are the only variables, it cannot be done, at least not directly by a tool like fsolve.
Can you create a helper function, that will solve the problem? Well, yes. For example, I want to optimize the objective f(x,y), and you refuse to reformulate it as essentialy f(xy), where xy is now a vector of length 2? I'll use fminunc here as an example...
Fun = @(x,y) (x-1).^2 + (x - y).^2 - x + y;
varsplit = @(XY) Fun(XY(1),XY(2));
fminunc(varsplit,[2,2])
So fminunc found the minimum of Fun, as a function of two variables.
More Answers (0)
See Also
Categories
Find more on Surrogate Optimization 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!