Clear Filters
Clear Filters

Why is my maxperf.m code not operating correctly

1 view (last 30 days)
p = [2, 5];
q = [1, 0, 1, 2, 2];
% Call the maxperf function
maxperf(p, q);
dp = 2
extremal_points = 0×1 empty double column vector max_J = 0×1 empty double column vector index = 0×1 empty double column vector maximizing_x = 0×1 empty double column vector Maximizing value of x: Maximal value of J(x):
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

Answers (1)

Steven Lord
Steven Lord on 21 Jul 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.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!