Code outputs correctly once, but gives an error message when I try to output a second time.
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Anthony Knighton
el 28 de En. de 2021
Comentada: Anthony Knighton
el 28 de En. de 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.
% Parameters
b=1;
c=0.25;
% Set the counter
n=1;
% Set the first value of a
a(1)=1;
% Repeat the calculation until a becomes smaller than the machine epsilon
while (a>eps())
% 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
n=n+1;
% Reduce the value of a by factor 0.1.
a(n)=a(n-1)/10;
end
I also have written code that plots the result.
% plot the results
p=loglog(a(1:n-1),abs(x2+0.25),'o',a(1:n-1),abs(x1+0.25),'s');
set(p(1),'Linewidth',2,'Color','red')
set(p(2),'Linewidth',2,'Color','blue')
xlabel('a','Fontsize',14)
ylabel(texlabel('|x - x_0|'),'Fontsize',14) % x_0 = root at a=0
legend('lhs','rhs')
legend('Location','Southeast')
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?
0 comentarios
Respuesta aceptada
Alex Alex
el 28 de En. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!