How to retain only the positive root of a quadratic equation?

I was wondering if there is any Matlab function that would allow me to retain only the positive root of a quadratic equation. I want to use that function along with the 'roots' function to solve n number of quadratic equations to get n number of positive roots.
x=zeros(1,n)
for i=1:n
x(i)=function(roots([a(i) b(i) c(i)]))
end

 채택된 답변

Guillaume
Guillaume 2014년 8월 15일
To only get the positive elements of array a:
>>a = [-2.5 0 2.5 -3.5 1];
>>apos = a(a>=0)
apos =
0 2.5000 1.0000

댓글 수: 4

Matt J
Matt J 2014년 8월 15일
편집: Matt J 2014년 8월 15일
This has the opposite problem to Evan's answer. It doesn't handle imaginary roots
>> a=[1+i, -1+i, 3];
>> a(a>=0)
ans =
1.0000 + 1.0000i 3.0000 + 0.0000i
One should test both for positivity and realness.
Got it. Thanks.
Joel Matthew commented on the Answer:
did you read the question ? he is asking for finding the positive root not an element in an array
Joel,
roots() returns a vector of values. roots() is an already known step. The question is therefore to write a function which examines a vector of values and returns the positive (real) values from the vector. So where the original poster had written
x=zeros(1,n)
for i=1:n
x(i)=function(roots([a(i) b(i) c(i)]))
end
using "function" as a stand-in for the name of the function to do the desired selection, that could be written as
x=zeros(1,n)
for i=1:n
x(i)=Extract_positive(roots([a(i) b(i) c(i)]))
end
function apos = Extract_positive(a)
apos = a(a > 0);
which is code that only has to worry about elements of an array.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Evan
Evan 2014년 8월 15일
편집: Evan 2014년 8월 15일
help imag
So, if you wanted to return only roots without complex parts:
R_all = roots([1 1 0 1]);
R_real = R_all(~imag(R_all))

댓글 수: 4

That returns both the positive and the negative root. I think your code only discards IMAGINARY roots, not NEGATIVE roots.
Matt J
Matt J 2014년 8월 15일
편집: Matt J 2014년 8월 15일
It will discard not only imaginary roots, but any complex root with a non-zero imaginary part.
Thanks.
Evan
Evan 2014년 8월 15일
편집: Evan 2014년 8월 15일
Sorry! I would say I misread your question, but I originally used the word "positive" as well! My only excuse, then, is that it's a Friday. ;)

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

질문:

2014년 8월 15일

댓글:

2016년 9월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by