Making polynomial in matlab causes infinite loop
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Image Analyst
2015-11-1
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 个评论
Image Analyst
2015-11-2
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!