How to resolve this error "Unrecognize function or variable" when using fsolve

I am trying to solve a system of two equations with two varaibles using fsolve in live script. What primarily I want to do is to plot the suface of the output. Below are the
codes for the two scripts I used
First script:
function F = myfun(x)
F = nan(1,2)
F(1) = cosh(b.*a.^2*x(1)^2 + b.*(1-a).^2*x(2)^2)-x(1);
F(2) = cosh(2*b.*a.*(1-a)*x(1)*x(2) + b*.(1-a).^2*x(2)^2)-x(2);
end
Second script;
b = linspace(-2,2,100);
a = linspace(0,1,100);
x0 = [0,0];
x = fsolve(@(x)myfun(x),x0)
Z = a.*x(1) + (1-a).*x(2)
figure
[X,Y] = meshgrid(b,a);
surf(Y,X,Z')
Edit: This is the error message I get
Unrecognized function or variable 'b'.
Error in myfun (line 3)
F(1) = cosh(b*a^2*x(1)^2 + b*(1-a)^2*x(2)^2)-x(1);
Error in myfunTanh (line 9)
x = fsolve(@(x)myfun(x),x0)
Error in fsolve (line 260)
fuser = feval(funfcn{3},x,varargin{:});
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.

Respuestas (1)

Matt J
Matt J el 17 de Jul. de 2021
Editada: Matt J el 17 de Jul. de 2021
We need to see the full error message copy/pasted, but you may have put the myfun() script in a location where Matlab cannot see it.
Also, you are not passing a and b to myfun(), so myfun() sees them as undefined.
Also, a and b are vectors in your second script, but treated as scalars within myfun, so you need to resolve that as well.

3 comentarios

After is I made it element wise operation and included it 'a' and 'b' in the myfun(), I got this error;
Unable to perform assignment because the left and right sides have a different number of elements.
Error in myfun (line 3)
F(1) = cosh(b.*a.^2*x(1)^2 + b.*(1-a).^2*x(2)^2)-x(1);
Error in myfunCosh (line 9)
x = fsolve(@(x)myfun(x,a,b),x0)
Error in fsolve (line 260)
fuser = feval(funfcn{3},x,varargin{:});
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.
You assign a vector of 100 values (cosh(...)) to one scalar element (F(1)).
Same for F(2).
So you will have to call fsolve in a loop 100 times instead.
"Also, a and b are vectors in your second script, but treated as scalars within myfun, so you need to resolve that as well."

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Productos

Versión

R2021a

Preguntada:

el 17 de Jul. de 2021

Comentada:

el 17 de Jul. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by