How to use fsolve with an array, to produce an array of answers?

4 views (last 30 days)
Hey,
I have three simultaneous equations which I have been using to solve with fsolve. There is a constant, B, in these equations which so far I have been manually setting to the desired number needed, however, this method is extremely inefficient.
What i want to be able to do is set this variable to be an array between 1/3 and 3 with an increase of 0.01 between elements, and have fsolve solve for each element in the array.
The three equations are:
F(1)=(B.*u(1))+(B./(u(2)-u(1))^2)+(B./(u(3)-u(1))^2);
F(2)=u(2)-(B./(u(2)-u(1))^2)+(1/(u(2)-u(3))^2);
F(3)=u(3)-(B./(u(3)-u(1))^2)-(1/(u(3)-u(2))^2);
where B is the array I wish to use, with B=[(1/3):0.01:3].
I am wondering if it is possible to run this so that I can have an array for each variable I want u1, u2 and u3? I am stuck because I am not sure what to do when setting the initial conditions for fsolve, as these would probably also have to be set in an array. I hope this description is sufficient enough for you to understand. Thankyou

Accepted Answer

Walter Roberson
Walter Roberson on 30 Nov 2015
B = (1/3) : 0.01 : 3;
%UINIT should be a cell array with one initializer per cell
%I just make something up here
%note: if you want to use the same initializer for all of them you can use simpler code
UINIT = mat2cell( rand(3, length(B)), 3, ones(1,length(B)) );
system = @(u,b) [ (b.*u(1))+(b./(u(2)-u(1))^2)+(b./(u(3)-u(1))^2),
u(2)-(b./(u(2)-u(1))^2)+(1/(u(2)-u(3))^2),
u(3)-(b./(u(3)-u(1))^2)-(1/(u(3)-u(2))^2) ];
UVALS = arrayfun( @(b,uinit) fsolve(@(x) fsolve(x, b), uinit{1}), B, UINIT, 'Uniform', 0);
Now UVALS will be a cell array with each entry being a solution; UVALS{K} will be the u values corresponding to B(K)
  2 Comments
Feynman94
Feynman94 on 30 Nov 2015
Thanks Walter for your really quick response. I input this method into matlab, however the UVALS line returned these errors:
??? Error using ==> lsqfcnchk at 111 FUN must be a function, a valid string expression, or an inline function object.
Error in ==> fsolve at 228 funfcn = lsqfcnchk(FUN,'fsolve',length(varargin),funValCheck,gradflag);
Error in ==> @(x)fsolve(x,b)
Error in ==> fsolve at 248 fuser = feval(funfcn{3},x,varargin{:});
Error in ==> @(b,uinit)fsolve(@(x)fsolve(x,b),uinit{1})
Caused by: Failure in initial user-supplied objective function evaluation. FSOLVE cannot continue.
Walter Roberson
Walter Roberson on 30 Nov 2015
UVALS = arrayfun( @(b,uinit) fsolve(@(x) system(x, b), uinit{1}), B, UINIT, 'Uniform', 0);

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!