Function returns ans, how to exclude?

1 visualización (últimos 30 días)
Sveinar Bjørnseth
Sveinar Bjørnseth el 7 de Oct. de 2020
Editada: Stephen23 el 8 de Oct. de 2020
Good evening,
I am trying to write a script that returns 2 answer for the quadratic equation.
And I want to be able to input whatever values for a,b,c I want.
I have written this in the script:
function [x1,x2] = quad_equation(a,b,c)
prompt = 'a = ';
a = input(prompt);
prompt2 = 'b = ';
b = input(prompt2);
prompt3 = 'c = ';
c = input(prompt3);
x1=(-b+sqrt(b.^2-4.*a.*c))/(2.*a)
x2=(-b-sqrt(b.^2-4.*a.*c))/(2.*a)
end
It runs fine, but it outputs with "ans" at the end, and I can't figure out how to get rid of it.
Output:
x1 =
1
x2 =
-4
ans =
1
Any suggestions? :)
  1 comentario
Stephen23
Stephen23 el 8 de Oct. de 2020
Editada: Stephen23 el 8 de Oct. de 2020
What is the point in defining a fucntion with three input arguments, which are then totally ignored?
function [x1,x2] = quad_equation(a,b,c)
prompt = 'a = ';
a = input(prompt);
prompt2 = 'b = ';
b = input(prompt2);
prompt3 = 'c = ';
c = input(prompt3);
Get rid of all of those input calls, input makes functions untestable, unrepeatable, ungeneralizable, unexpandable.

Iniciar sesión para comentar.

Respuestas (2)

Walter Roberson
Walter Roberson el 7 de Oct. de 2020
Change
x1=(-b+sqrt(b.^2-4.*a.*c))/(2.*a)
x2=(-b-sqrt(b.^2-4.*a.*c))/(2.*a)
to
x1=(-b+sqrt(b.^2-4.*a.*c))/(2.*a);
x2=(-b-sqrt(b.^2-4.*a.*c))/(2.*a);
Then, when you run your function, be sure to assign the results to variables, and be sure to put a semi-colon at the end of the line:
[first, second] = quad_equation(83,-5,-9);

madhan ravi
madhan ravi el 7 de Oct. de 2020
[x1, x2] = quad_equation
function [x1, x2] = quad_equation
prompt = 'a = ';
a = input(prompt);
prompt2 = 'b = ';
b = input(prompt2);
prompt3 = 'c = ';
c = input(prompt3);
x1=(-b+sqrt(b.^2-4.*a.*c))/(2.*a);
x2=(-b-sqrt(b.^2-4.*a.*c))/(2.*a);
end

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by