Don't know how to fix error preallocating for speed

3 ビュー (過去 30 日間)
Kameron
Kameron 2023 年 3 月 3 日
コメント済み: the cyclist 2023 年 3 月 3 日
Keep getting an error for preallocating for speed, but I don't know how to fix it
% March/2023
%
% Solve f(x) = exp(x)-x.^2+3*x-2 using false-position method.
%
% The function is defined in func(x);
%
% Input
tol = 1.e-5;
a = 0.0;
b = 1.0;
nmax = 100;
% Initialization
itcount = 0;
error = 1.0;
% Graph of the function
xval = linspace(a,b,100);
for i=1:10
fval(i) = func(xval(i));
end
Unrecognized function or variable 'func'.
plot(xval,fval);
grid on;
hold on;
% iteration begins here
while (itcount <= nmax && error >= tol)
itcount = itcount + 1;
xold = x;
% Generate and save iteratres
fa = func(a);
fb = func(b);
x = a - ((b - a)/(fb - fa))*fa;
z(itcount) = x;
fx = func(x);
error = abs(fx);
% error = abs(x - xold);
if (error < tol)
x_final = x;
else
if (fa*fx < 0)
% root is between a and x
b = x;
else
% root is between x and b
a = x;
end
end
plot(z(1:itcount),zeros(itcount,1),'r+');
pause(2)
end
if (itcount < nmax);
val = func(x);
fprintf(1,'Converged solution after %5d iterations',itcount);
fprintf(1,' is %15.7e, %e \n',x_final, val);
else
fprintf(1,'Not converged after %3d iterations',nmax);
end
  6 件のコメント
Kameron
Kameron 2023 年 3 月 3 日
That must be the issue, how could I include a function block at the end?
the cyclist
the cyclist 2023 年 3 月 3 日
I already showed you how to do this. Include this line before the first time you use func:
func = @(x) exp(x)-x.^2+3*x-2

サインインしてコメントする。

回答 (1 件)

Star Strider
Star Strider 2023 年 3 月 3 日
It’s likely not an error, simply a suggestion that preallocating for speed would be advisable. (A preallocated loop generally requires about 20% less time compared to not preallocating.) It is most likely to appear with respect to a loop that stores values. The only one that I can see where that would work is:
for i=1:10
fval(i) = func(xval(i));
end
because it has a fixed number of iterations.
It could also work in the while loop because you are storing ‘z’, however unless you know about how many iterations that loop would require, preallocating would simply be a guess. One way to do that in the while loop would be to preallocate with perhaps:
z = NaN(1,1000);
and when the loop finishes, use the rmmissing function to remove any remaining NaN values.
x = [1 2 3 4 5 NaN NaN]
x = 1×7
1 2 3 4 5 NaN NaN
x = rmmissing(x)
x = 1×5
1 2 3 4 5
This assumes that the calculation of ‘x’ never produces a NaN value.
The preallocation statements would be placed just before their respective loops.
.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by