fsolve function random value gives the same output as random value
1 view (last 30 days)
Show older comments
Hello everyone, I am using fsolve by calling in
fun = @theta;
x0 = rand(5,5);
rjm = fsolve(fun,x0);
This works without any loops. However, when there are loops the value from fsolve "rjm" is the same as rand(5,5). Is there something I made a mistake?
function F = theta(x)
psi = [-2,-4,-6,-8,-10];
ffr = linspace(0.05,0.1,5);
phi = 36;
omega = phi.*(1+psi)./(phi.*(1+psi)-1);
for i = 1:length(psi)
for j = 1:length(ffr)
F = 1 + (x(i,j) - ffr(j))/(1+x(i,j))*omega(i)/(1-omega(i))+ psi(i)*((1+x(i,j))/(1+mean(x(i,j)))).^(omega(i)/(1-omega(i)));
end
end
0 Comments
Answers (1)
John D'Errico
on 30 Nov 2021
Edited: John D'Errico
on 30 Nov 2021
First, always test how your function operates. That will verify it produces what you expect.
theta(ones(5,5))
theta(rand(5,5))
Do you see it? theta returns a SCALAR RESULT.
Fsolve is a solver that tries to solve systems of equations. Here, you have 25 unknowns, as the elements of a 5x5 matrix. Can fsolve find a single set of parameters for that matrix, that will produce theta==0?
You have ONE equation that theta implicitly produces, but 25 unknowns.
Perhaps you want to use an optimizer, perhaps one that will minimize or maximize theta.
x0 = rand(5,5)
opts.Display = 'iter';
[xfinal,fval,exitflag] = fminunc(@theta,x0,opts)
So fminunc essentially found the function is unbounded. Apparently it could make that happen by setting x(5,5)=-1.
function F = theta(x)
psi = [-2,-4,-6,-8,-10];
ffr = linspace(0.05,0.1,5);
phi = 36;
omega = phi.*(1+psi)./(phi.*(1+psi)-1);
for i = 1:length(psi)
for j = 1:length(ffr)
F = 1 + (x(i,j) - ffr(j))/(1+x(i,j))*omega(i)/(1-omega(i))+ psi(i)*((1+x(i,j))/(1+mean(x(i,j)))).^(omega(i)/(1-omega(i)));
end
end
end
Regardless, fsolve is arguably not the correct tool to solve your problem, since it cannot solve ONE equation with 25 unknowns. Since I don't really know what problem you wanted to solve, I am at a loss beyond this point.
I do have one serious issue with the function theta. Note that inside of the loop, you set F to a scalar value. It does so repeatedly. Perhaps you really intended to create a MATRIX F(i,j). So the ONLY value that ever gets returned is essentially F(5,5). And that explains why fminunc only bothered to iterate on the element x(5,5).
But this is just idle speculation on my part.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!