for loop to find roots of a complicated multivariable function

4 views (last 30 days)
hello,
I want to find all the possible roots of the function called gammameta in the script considering all the possible values in the ranges for theta and r .
I did it by using fzero but it only gives me one of all the possible roots for each case.
Now I know I have to use the function roots() but I do not know hot to put gammameta in the roots function syntax in such a way Matlab can perform the for loop to consider all the values of theta and r. Also I do not know hot to enter in roots that x is to the power of 1-s.
Thank you.
s=0.4;
rho=0.01;
b=2.5;
tau=0.286;
x0=0.099;
%ranges
theta_pool = 0.01:0.01:0.75;
r_pool = 0.02:0.001:0.035;
beta_pool= 0:0.001:0.2;
%Call fsolve in a loop
for i = 1 : numel(theta_pool)
theta = theta_pool(i);
for j = 1: numel(r_pool)
r = r_pool(j);
gamameta= @(x,s,rho,b,tau,theta,r)((r*((1-tau)*s*(x^(1-s))*(1-theta))/(r-theta*(1-tau)*s*x^(1-s)))- rho -(x^(s)/b)-r+tau/b);
F= @(x)gamameta(x,s,rho,b,tau,theta,r);
xsol(i,j)= fzero(F,x0);
xtrans =xsol';
x_pool= xtrans(:)';
end
end

Answers (1)

Deepak
Deepak on 12 Dec 2024
To find all real roots of the function “gammameta” without encountering complex values, use “fzero” with multiple initial guesses.
Define a range of “initial guesses” and modify “gammameta” to consider only its real part. Before applying “fzero”, ensure the function value at each initial guess is real. Iterate over these guesses and parameter ranges, storing only unique real roots. This approach leverages robustness of “fzero” while avoiding complex value regions.
Here is the modified MATLAB code to achieve the same:
s = 0.4;
rho = 0.01;
b = 2.5;
tau = 0.286;
% ranges
theta_pool = 0.01:0.01:0.75;
r_pool = 0.02:0.001:0.035;
initial_guesses = 0.01:0.01:1.0; % Range of initial guesses for fzero
% Store all unique roots
unique_roots = [];
for i = 1:numel(theta_pool)
theta = theta_pool(i);
for j = 1:numel(r_pool)
r = r_pool(j);
gammameta = @(x) real((r * ((1-tau) * s * (x^(1-s)) * (1-theta)) / ...
(r - theta * (1-tau) * s * x^(1-s))) - rho - ...
(x^s / b) - r + tau / b);
for x0 = initial_guesses
try
% Check if the initial function value is real
if isreal(gammameta(x0))
root = fzero(gammameta, x0);
% Store only unique roots
if isempty(unique_roots) || all(abs(unique_roots - root) > 1e-6)
unique_roots = [unique_roots, root];
end
end
catch
% Handle cases where fzero fails to find a root
continue;
end
end
end
end
disp('Unique roots found:');
disp(unique_roots);
Please find attached the documentation of functions used for reference:
I hope this will help in resolving the issue.

Categories

Find more on Loops and Conditional Statements 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!