"Index exceeds array bounds" error; can't resolve

I'm making a function to find min and max of a function (cubic) between a set interval; I keep trying to run my test cases but run into "index exceeds array bounds" in my line 11 (j = g(2)). Some of the individual cases run fine, but it seems that some don't (noticeably the one with a interval of [0, 1.7] which may be a clue.
function rslt = polyMinMax(a,b,c,d,e,f)
% We have defined rslt to be the final result with the min and max
% values both for x and y
polyMinMax1 = [c, d, e, f];
% This step we take the derivative of the polynomial and get
% polyMinMax' (prime) which is g
g = polyder(polyMinMax1);
h = g(1);
j = g(2);
k = g(3);
% equivalent to a,b,c in normal quad formula
% This step we look for the solutions given the m parameter
m = j^2-4*h*k;
% the discriminant; v1 is positive; v2 is negative
if m > 0
if j >= 0
v1 = (2*k)/(-j-sqrt(m));
v2 = (-j-sqrt(m))/(2*h);
else
v1 = (-j-sqrt(m))/(2*h);
v2 = (2*k)/(-j+sqrt(m));
end
elseif m == 0
v1 = (-j)/(2*h);
v2 = NaN;
else
v1 = NaN;
v2 = NaN;
end
q = [v1, v2, a, b];
x1 = min(q);
x2 = max(q);
y1 = c*(x1)^3+d*(x1)^2+e*(x1)+f;
y2 = c*(x2)^3+d*(x2)^2+e*(x2)+f;
rslt = [x1, x2, y1, y2];
Any ideas? I was thinking it had to do something with j and k being cell arrays and h being a normal character array (since the error starts with j and k and never has been h). I put my test cases below.
-->
rslt = zeros(8,4);
rslt(1,:) = polyMinMax(-1,2,-1,2,-1,1);
rslt(2,:) = polyMinMax( 1,2,1,-2,-1,1);
rslt(3,:) = polyMinMax(-2,1,4,8,-4,-2);
rslt(4,:) = polyMinMax(-1,2,1,0,1,-3);
rslt(5,:) = polyMinMax(-0.3,0.6,1.0e-14,9,-3,0);
rslt(6,:) = polyMinMax(-1,2,0,0,0,1.7);
rslt(7,:) = polyMinMax(0,3,-3,9,-1.0e-14,0);
rslt(8,:) = polyMinMax(0,1,0,-2,3,-1);
fprintf(1, '%11.6g %11.6g %11.6g %11.6g\n', rslt');

 Accepted Answer

You take the derivative of polyMinMax1 = [c, d, e, f] . If c is non-zero then you would expect to get back a vector of three results, [3*c, 2*d, e] . But if c is zero then you will not get back [0, 2*d, e] : leading zeros are omitted, so you would get back [2*d, e], a vector of length 2. If c and d are both zero, then you would get back [e], a vector of length 1.
rslt(6,:) = polyMinMax(-1,2,0,0,0,1.7);
Right there, c and d are both 0.

3 Comments

Ah I see what you mean; makes sense. Thanks! Now I need to go about finding a soln! :)
LastN = @(M, N) M(end-N+1:end);
ZPadN = @(M, N) LastN( [zeros(1, N), M], N);
g = ZPadN( polyder(polyMinMax1), 3);
Endless thanks! I was trying to use if statements to work it but couldn't get it. Infinite thanks.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!