"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');

 採用された回答

Walter Roberson
Walter Roberson 2018 年 9 月 18 日

0 投票

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 件のコメント

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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by