How to get real root of a function using fminbnd?
Mostra commenti meno recenti
Hello, How can I force MATLAB to only give real solutions to a math function using fminbnd?
This is my code:
x=-1:0.01:8; y=@(x) (x).^(4/3); yinv=@(x) -((x).^(4/3)); x_1=-1; x_2=8;
[xmin, ymin]=fminbnd(y,x_1,x_2);
[xmax, ymax]=fminbnd(yinv,x_1,x_2);
fprintf('The local maximum is %.2f at x = %.2f\n', -ymax, xmax)
fprintf('The local minimum is %.2f at x = %.2f\n', ymin, xmin)
Gives this as output:
The local maximum is 16.00 at x = 8.00 % Good. This is what it's supposed to be based on the x domain
The local minimum is -0.50 at x = -1.00 % This is the problem. (-1)^(4/3)=1 (The real solution)
Also, when I test in the Command Window:
(-1)^(4/3)
I get
-0.5000-0.866i
I think my code is spitting out the real part of (-1)^(4/3) that I get in Command Window.
Thanks for your help
1 Commento
John D'Errico
il 30 Apr 2025
Spostato: John D'Errico
il 30 Apr 2025
I think you are confused. FMINBND is a MINIMIZER. It does not compute a root. If the minimum of your objective can be negative, you will get it.
You want to use fzero to compute a root. Even at that, you need to understand that raising a negative number to a fractional power has a complex result as the primary solution.
Risposta accettata
Più risposte (1)
x=-1:0.01:8; y=@(x) (x).^(4/3); yinv=@(x) -((x).^(4/3)); x_1=-1; x_2=8;
[xmin, ymin]=fminbnd(y,x_1,x_2);
[xmax, ymax]=fminbnd(yinv,x_1,x_2);
fprintf('The local maximum is %.2f at x = %.2f\n', -ymax, xmax)
fprintf('The local minimum is %.2f+%.2fi at x = %.2f\n', real(ymin), imag(ymin), xmin)
fprintf() ignores the imaginary component of numbers.
5 Commenti
Walter Roberson
il 30 Apr 2025
Modificato: Walter Roberson
il 30 Apr 2025
This is the closest you can get to forcing MATLAB to only give real solutions to a math function using fminbnd
x=-1:0.01:8; y=@(x) (x).^(4/3); yinv=@(x) -((x).^(4/3)); x_1=-1; x_2=8;
opts = optimset('FunValCheck', 'on');
[xmin, ymin] = fminbnd(y, x_1, x_2, opts);
[xmax, ymax] = fminbnd(yinv, x_1, x_2, opts);
fprintf('The local maximum is %.2f at x = %.2f\n', -ymax, xmax)
fprintf('The local minimum is %.2f+%.2fi at x = %.2f\n', real(ymin), imag(ymin), xmin)
Walter Roberson
il 30 Apr 2025
I sort of lie a little:
You can set an option OutputFcn that checks the appropriate condition and records the current coordinates if the condition passes, and signals "stop" if the condition does not pass; then once the function finishes, retrieve the recorded coordinates.
rezheen
il 30 Apr 2025
((-1).^4).^(1/3)
Categorie
Scopri di più su Introduction to Installation and Licensing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!