I have a matrix which is 2x1 that contains the roots of a quadratic polynomial. How do I assign a variable to only take the positive root?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Henn
el 8 de Sept. de 2017
Respondida: John D'Errico
el 8 de Sept. de 2017
I have this code, shown below, to obtain the roots of a quadratic equation. How do I assign the variable alpha_1 to always take the positive root calculated in root_Fit.
root_Fit = roots(p_FiT)
alpha_1 = root_Fit(2)
0 comentarios
Respuesta aceptada
Más respuestas (1)
John D'Errico
el 8 de Sept. de 2017
Are you ABSOLUTELY certain that both roots are not positive? Are you absolutely certain that the roots are not complex?
The point is, what will you do if two of the roots are positive? Will you take the larger of the two? Will you generate an error? Complex roots? Two negative roots?
Good code looks for these events. It worries about them, making sure it knows what to do under ANY possible eventuality. Long ago, a good friend of mine would drop by and we would talk. Perhaps he had a date, whatever. He was the kind of person who wanted to plan for every eventuality. Not just what if his car "broke down" on the way to pick up his date, but what if he ran out of gas, had a flat tire, if he ran into a deer on the road, if a UFO landed on his roof. He had plans for all possible events. As I think about it, he would have made a good programmer in that respect.
Now, if you ABSOLUTELY know that a UFO will never land on the roof of your car, then there is no need to worry about it. Ok, bad example. :) But having a plan for what to do if you run out of gas, or have a flat, etc., is a good idea. It may be to call AAA.
Oh well, all of this may be moot. But it is worthwhile thinking about as you learn to program.
For a simple answer to your question...
If you KNOW that one root will always be positive, and the other negative, then this will suffice:
alpha_1 = max(root_Fit);
In fact, if both roots were positive, and you are willing to take the larger root, it will work too. It would fail with a pair of negative roots, and of course with complex roots.
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing 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!