Making polynomial in matlab causes infinite loop
1 view (last 30 days)
Show older comments
I am trying to make a polynomial function for several different coefficients. The problem is, something is wrong with my loop and matlab says
Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your available stack space can crash MATLAB and/or your computer.
I think the loop might be running infinitely, but I'm not sure how to fix this. I know matlab has a similar example for makeParabola, but I tried out their code and I get the same error.
function p = makePolynomial(a,b,c,d)
p = @polynomial
function y = polynomial(x)
y = a*x.^3 + b*x.^2 + c*x + d;
end
firstp = makePolynomial(0,1,0,0);
secondp = makePolynomial(1,-3,0,1);
thirdp = makePolynomial(0,0,1,-1);
range = [-4,4];
figure;
hold on
fplot(firstp, range);
fplot(secondp, range, 'r:');
fplot(thirdp, range, 'ko');
hold off
end
0 Comments
Accepted Answer
Image Analyst
on 1 Nov 2015
You have makePolynomial() calling itself, makePolynomial(). Why do you have this?
And why do you even have the unnecessary function polynomial()? It's not needed. What you do need is to make up a range for x. How does your code know if x has a thousand points from 3000 to 3489, or 150 points in the range 37 to 194, or whatever? It knows if you tell it, which you have not done. So assign some x - you might use linspace() for that -- then simply have this:
function p = makePolynomial(a,b,c,d)
% Get x somehow......
p = a*x.^3 + b*x.^2 + c*x + d;
figure
plot(x, p, 'b*-', 'LineWidth' 2, 'MarkerSize', 8);
grid on;
If you want, you can have a test script to call this function with different a,b,c,d values:
makePolynomial(0,1,0,0); % Plotting is done inside
makePolynomial(1,-3,0,1);
makePolynomial(0,0,1,-1);
But of course, don't put that inside the makePolynomial() function itself!!!
You can either have the plotting done inside the function, like I did, or you can return the output and "x" into your test script, and plot it in the test script rather than the makePolynomial() function -- it's your choice.
4 Comments
Image Analyst
on 2 Nov 2015
You should have two m-files. One function file called makePolynomial.m, and another to call that serrveral times with different values of a,b,c,d called testMakePolynomial.m, though you can call it one at a time from the command window if you want.
More Answers (0)
See Also
Categories
Find more on Polynomials in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!