Code outputs correctly once, but gives an error message when I try to output a second time.
2 views (last 30 days)
Anthony Knighton on 28 Jan 2021
I have written the following code that evaluates the roots of the quadratic function . The coefficients b and c input parameters. The initial value of a is 1. Each time it determines the roots, it decreases the value of a by . It does this until a becomes smaller than the machine epsilon.
% Set the counter
% Set the first value of a
% Repeat the calculation until a becomes smaller than the machine epsilon
% Calculate the quantity inside the square root
d = b^2-4*a(n)*c;
% Evalulate the regular expression
x1(n) = (-b+sqrt(d))/(2*a(n));
% Expression suitable for numerical calculation
x2(n) = -2*c/(b+sqrt(d));
% Output the results
fprintf('a= %22.16e, lhs=%22.16e, rhs=%22.16e \n',a(n),x1(n),x2(n));
% Increment the counter
% Reduce the value of a by factor 0.1.
I also have written code that plots the result.
% plot the results
ylabel(texlabel('|x - x_0|'),'Fontsize',14) % x_0 = root at a=0
However, I am having a strange experience. When I first wrote this program, it ran perfectly. It outputted all of the values of a and both of the roots for each iteration until a reached machine epsilon, and it also outputed the graph. When I ran the program a 2nd time without changing any code, it gave me the follwing error message: "Error using loglog. Vectors must be the same length". In order to get the code to run again, I actually had to delete the file and copy and paste the code into a different file. Why does this happen?
Alex Alex on 28 Jan 2021
I think that just in the workspace there was an array a, which has different dimensions with arrays x1 and x2. Use the clear command at the beginning of the code to free up the workspace. It should help.