fsolve: How can I adress my variables to x(1)?
2 次查看(过去 30 天)
显示 更早的评论
Hello, everybody,
In my program I need to use fsolve, but don't know how to adress my variables to the x(1), x(2), etc. that needs fsolver.
I give you simplified example:
My program in a certain pointt gives me (x, y are variables):
y = 2*x
y = x^4
and I want to receive the solution: [2,2]
I can get if I do this:
----------------
function F=myfun(x)
F = [x(2)-x(1)^2 ; x(2)-2*x(1)];
end
fsolve(@myfun,[3,3])
--------------------------
But I can't do manually because my program has many and very complex equations. I need a way to adress my equations to the fsolve form.
1 个评论
Walter Roberson
2019-8-24
Would you happen to have the Symbolic Toolbox? It often makes this kind of task easier.
回答(2 个)
Matt J
2019-8-24
编辑:Matt J
2019-8-24
I don't understand your question very well, but maybe it will help to mention that fsolve does not require you to express the function in terms of individual x(i). fsolve does not know or care how the function is expressed in code. It only cares that the function is differentiable.
For example, I could conceivably solve a linear system of equations as below, which uses no x(i) references at all:
A=rand(5); b=A*[1;2;3;4;5]
x=fsolve(@(x) A*x-b, ones(5,1))
x =
1.000000000000000
1.999999998886354
2.999999996241878
4.000000002442892
5.000000000534329
1 个评论
Matt J
2019-8-24
Of course, you would never actually use fsolve to solve a linear system. Matlab has better solvers for that.
Diego R
2019-8-25
编辑:Diego R
2019-8-25
4 个评论
Matt J
2019-8-25
编辑:Matt J
2019-8-25
But I know in which stretch I have to search....This is the reason of using fsolve.
That's not the right reason to choose fsolve over the symbolic solver. The reason why a non-symbolic solver might be preferable for you is that you said you had many complicated equations. That makes it less likely that a symbolic solution exists.
If you want to try to solve symbolically, you could use the assume() command to specify bounds.
To solve non-symbolically, you should not use fsolve, but rather lsqnonlin, which has input arguments for specifying bounds on the variables. If your question is about how to convert symbolic equations to a form usable by non-symbolic solvers, you should use matlabFunction().
Walter Roberson
2019-8-25
solve() does not always respect assumptions.
fsolve() does not permit bounds to be specified. fzero() does permit bounds to be specified, but only supports a single function of a single variable.
If I recall correctly, fsolve() and fzero() assume continuity, which could be a problem with piecewise functions.
vpasolve() permits bounds to be specified for each variable.
>> solve(y==2*x, y==x^2,x>0)
ans =
struct with fields:
x: [1×1 sym]
y: [1×1 sym]
>> [ans.x,ans.y]
ans =
[ 2, 4]
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!