how can I preallocate for speed in a loop?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
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
0 commentaires
Plus de réponses (0)
Voir également
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!