Don't know how to fix error preallocating for speed

1 view (last 30 days)
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 Comments
the cyclist
the cyclist on 3 Mar 2023
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

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 3 Mar 2023
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.
.

Tags

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!