max value of a function
73 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
123456
el 8 de Ag. de 2022
Comentada: 123456
el 11 de Ag. de 2022
Hello everyone. I'm having a problem with finding a maximum y of a function. In general I use:
x= double(solve(diff(func)));
ymax=eval(func);
But in some cases this gives me a solution that is clearly not the maximum. Let's say, that the function is:
func = exp(-(x - 1)^2) + exp(-(x + 2)^2)
if i try to use max() i get an error "Input arguments must be convertible to floating-point numbers.".
Please let me know where is the mistake in my thinking.
0 comentarios
Respuesta aceptada
Matt J
el 8 de Ag. de 2022
Editada: Matt J
el 8 de Ag. de 2022
In general I use: x= double(solve(diff(func)));
This assumes there are no local min/max or saddle points.
if i try to use max() i get an error "Input arguments must be convertible to floating-point numbers.".
You cannot use max() with symbolic variables.
8 comentarios
Matt J
el 9 de Ag. de 2022
Editada: Matt J
el 9 de Ag. de 2022
If you can identify a finite search interval [a,b] where the solution lies, you can do something like this:
a=-10; b=+10;
func = @(x) exp(-(x - 1).^2) + exp(-(x + 2).^2); %Note the element-wise .^
X=linspace(a,b,1e4);
Y=func(X);
[~,i0]=max(Y);
[xmax,ymax] = fminbnd(@(z) -func(z), X(i0-1), X(i0+1));
ymax=-ymax;
fplot(func,[a,b]); hold on
plot(xmax,ymax,'or','MarkerSize',10); hold off; axis padded
Más respuestas (1)
Torsten
el 8 de Ag. de 2022
Editada: Torsten
el 8 de Ag. de 2022
syms x
func = exp(-(x - 1)^2) + exp(-(x + 2)^2);
dfunc = diff(func,x);
ddfunc = diff(dfunc,x);
xc= double(vpasolve(dfunc==0,[0 2]))
xnum = double(subs(ddfunc,x,xc));
if xnum < 0
disp('Local maximum');
elseif xnum == 0
disp('Unknown type')
else
disp('Local minimum')
end
funcnum = matlabFunction(func);
x = 0:0.01:2;
plot(x,funcnum(x))
0 comentarios
Ver también
Categorías
Más información sobre Numbers and Precision en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!