how can I preallocate for speed in a loop?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
StefBu
2019-1-24
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!