"Index exceeds array bounds" error; can't resolve
Show older comments
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
More Answers (0)
Categories
Find more on Matrix Indexing 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!