필터 지우기
필터 지우기

how can I preallocate for speed in a loop?

조회 수: 1 (최근 30일)
Vickie Guzman
Vickie Guzman 2019년 1월 24일
답변: StefBu 2019년 1월 24일
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

채택된 답변

StefBu
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개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by