How to use fsolve with input from an array and store output in an array?

19 views (last 30 days)
The equation in my function requires input of values stored in an array, and I want to solve the equation for each value in that array and store the corresponding solutions in a new array. I think I just have some sort of syntax error.... Maybe do I need to include a while loop in the function itself?
K=[400:600];
q=1; %intialize counter
x_e = zeros(1,201); % assign an array of zeros for x_e
while q<202
x0 = 0;
out = fsolve(@funct,x0)
x_e(1,q) = out; % store the value of the solved equation in an array
q=q+1;
end
function F = funct(x)
F = (x/(1.5-(2.*x)))./ ( ( (0.5-x)./(1.5-(2.*x))).* (( (1-(2.*x))./(1.5-(2.*x)))^2) )-K(q);
end

Answers (1)

Walter Roberson
Walter Roberson on 22 Sep 2015
As a guess:
K=[400:600];
numK = length(K);
x_e = zeros(1,numK); % assign an array of zeros for x_e
for q = 1 : numK
x_e(1,q) = fsolve(@funct,K(q));
end
Or more simply,
K=[400:600];
x_e = arrayfun(@(x0) fsolve(@funct,x0), K);
with no loop.
  2 Comments
Lea Winter
Lea Winter on 22 Sep 2015
Thanks! I tried using this (and some other similar forms of what you suggested, for example changing K to a single variable value instead of an array and removing the loop), and I seem to keep getting the same error. Maybe there is something wrong with the function? Maybe a different argument needs to be used other than "x", for example, "x(q)"?
function F = funct(x)
Here is the error message:
Error using feval Undefined function 'funct' for input arguments of type 'double'.
Error in fsolve (line 241) fuser = feval(funfcn{3},x,varargin{:});
Caused by: Failure in initial user-supplied objective function evaluation. FSOLVE cannot continue.
Walter Roberson
Walter Roberson on 22 Sep 2015
funct = @(x,K) (x./(1.5-(2.*x))) ./ ( ( (0.5-x)./(1.5-(2.*x))).* (( (1-(2.*x))./(1.5-(2.*x))).^2) ) - K;
K=[400:600];
guess = 0.1; %must be at least .055049 to work with this funct
for q = 1 : length(K)
guess = fzero(@(x) funct(x, K(q)), guess);
x_e(1,q) = guess;
end

Sign in to comment.

Categories

Find more on MATLAB 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!