How to use fsolve with input from an array and store output in an array?
22 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
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
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
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!