Index exceeds the number of array elements (1).

2 views (last 30 days)
Hello I am getting the following error when running this function in MATLAB:
Index exceeds the number of array elements (1).
Error in hw6_1 (line 11)
err = min(abs(f(a)),abs(f(b)));
Thank you!!
function [root, A, B] = hw6_1(f, a, b, numsegs)
%f = function
%a = lower limit of the initial range
%b = upper limit of the intial range
%numsegs = number of subranges
%root=number of roots
%A=vector of lower limits
%B=vector of upper limits
A=a;
B=b;
tol = 0.001;
err = min(abs(f(a)),abs(f(b)));
while (err >= tol)
dx = (b-a)/numsegs;
for i = 1:numsegs
x = a + (i-1)*dx;
prod = f(x) * f(x+dx);
if (prod <= 0)
a = x; %identify new subrange
b = x+dx;
A=[A,a];
B=[B,b];
end
end
err = min(abs(f(a)),abs(f(b)));
end
if (abs(f(a)) < abs(f(b)))
root = a;
else
root = b;
end
  4 Comments
Niccole Theriault
Niccole Theriault on 3 Mar 2021
Hi! I'm sorry, I'm pretty new to this. How do I fix it?
I need to have the function set to the user can input a funtion (f=2*x^2 for example), the bounds (a&b) and the number of segments to divide the bounds into.
Thanks again!
Walter Roberson
Walter Roberson on 3 Mar 2021
Do not pass
2*x^2
as the first parameter. Pass
@(x)2*x.^2

Sign in to comment.

Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!