Why is my maxperf.m code not operating correctly
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
p = [2, 5];
q = [1, 0, 1, 2, 2];
% Call the maxperf function
maxperf(p, q);
function maxperf(p, q)
% Compute the numerator polynomial of the derivative of J(x)
dp = polyder(p)
dJ_num = conv(dp, p) - conv(p, dp);
% Find the critical points where dJ(x)/dx = 0
extremal_points = roots(dJ_num)
% Evaluate J(x) at each extremal point
J_values = polyval(p, extremal_points).^2 ./ polyval(q, extremal_points);
% Find the maximizing value of J(x) and the corresponding x
[max_J, index] = max(J_values)
maximizing_x = extremal_points(index)
% Display the results
disp("Maximizing value of x:");
disp(maximizing_x);
disp("Maximal value of J(x):");
disp(max_J);
end
Réponses (1)
Steven Lord
le 21 Juil 2023
Move the lines where you define p and q and call maxperf out of the maxperf function. With those lines present, MATLAB will do one of two things.
Case 1:
If you call maxperf with two inputs it will run with those two inputs until it gets to the last line of the function. It will then call maxperf with the p and q vectors you defined inside maxperf as inputs.
It will run with those two inputs until it gets to the last line of the function. It will then call maxperf with the p and q vectors you defined inside maxperf as inputs.
It will run with those two inputs until it gets to the last line of the function. It will then call maxperf with the p and q vectors you defined inside maxperf as inputs.
It will run with those two inputs until it gets to the last line of the function. It will then call maxperf with the p and q vectors you defined inside maxperf as inputs. ...
Hopefully you see the pattern, that this will never stop (except MATLAB will detect the infinite recursion and stop itself with an error before it potentially crashes.)
Case 2:
If you call maxperf with no input argument, MATLAB will not "automatically detect" that you've defined variables p and q inside your function and use those as the inputs. It will instead error indicating you haven't provided enough input arguments to maxperf.
With those lines removed, you're in case 3:
If you call maxperf with two inputs it will run with those two inputs until it gets to the last line of the function. Then it will stop executing.
You probably also want to modify maxperf to return some of the variables you compute inside it, so you can use them in whatever code called maxperf.
2 commentaires
Voir également
Catégories
En savoir plus sur Startup and Shutdown dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!