how can I preallocate for speed in a loop?

1 vue (au cours des 30 derniers jours)
Vickie Guzman
Vickie Guzman le 24 Jan 2019
Réponse apportée : StefBu le 24 Jan 2019
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

Réponse acceptée

StefBu
StefBu le 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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by