Assigning roots as variables to a function

I have x^2+5*x+6=0.
I see the roots with the root command but i want to set them as variables to a new function. Also how can i set them to two different displays? I want to write down:
sprintf( 'the first root:%f and the second root:%f')

 Respuesta aceptada

Pat Gipper
Pat Gipper el 31 de Dic. de 2020
The output of the roots function can be assigned to a workspace array variable and printed out as you wanted. See the simple example below. You would have to adapt the formatting for complex roots.
x=roots([1,5,6]);
sprintf('the first root:%f and the second root:%f',x)

4 comentarios

Walter Roberson
Walter Roberson el 31 de Dic. de 2020
Note: all of the % formats for sprintf() and fprintf() ignore the complex portion of a value, so if you are dealing with complex values you should use real() and imag() to break them into pieces,
John Blaz
John Blaz el 31 de Dic. de 2020
Thank you for your reply.
This is my script:
clc
clear
a=input('input the first number at x^2:');
b=input('input the second number at x:');
c=input('input the third number:');
[x1,x2]=ad(a,b,c);
sprintf('first root is: %f,second root is: %f',x1,x2)
And this is my function:
function [x1,x2] = ad(a,b,c)
%second degree equation
f=[a b c];
y=([roots(f)])
y(1)=x1
y(2)=x2
end
What am i doing wrong, in order toassign the roots to x1 and x2?
Pat Gipper
Pat Gipper el 31 de Dic. de 2020
You just need to swap variables y and x in the function assignment,
x1=y(1);
x2=y(2);
John Blaz
John Blaz el 31 de Dic. de 2020
It worked thank you.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre MATLAB en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 30 de Dic. de 2020

Comentada:

el 31 de Dic. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by