how can I preallocate for speed in a loop?

1 view (last 30 days)
Hello,
This is my current code I keep getting an error about pre-allocating my x_p variable.
Would anyone know who I could fix it?
Thank you.
% bisection method
bisection = bisec(depth,x_l,x_u,10,.01);
function ANS = bisec( f, x_l, x_u, itera, error )
%BISEC bisection method
for i = 1:itera
x_p(i) = (x_l + x_u)/2;
if ((f(x_l)*f(x_p(i))) < 0)
x_u = x_p(i);
elseif ((f(x_l)*f(x_p(i))) > 0)
x_l = x_p(i);
elseif ((f(x_l)*f(x_p(i))) == 0)
break;
end
if ((i>1) && (abs((x_p(i)-x_p(i-1))/x_p(i)) * 100) < error)
break;
end
end
ANS = x_p(end);
end

Accepted Answer

StefBu
StefBu on 24 Jan 2019
Hi. Since x_p grows in each iteration of your for-loop you can easily define its size at the begining.
Just use this before your loop:
x_p = zeros(itera,1);
Greetings
Stefan

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!