About choosing negative and positive elements from vector of real, imaginary and complex numbers.

9 次查看(过去 30 天)
Hi here is my problem and thanks in advance for reading.
I solve an equation (eqn) that returns eight roots, they will be a mix of real, imaginary, and complex. I want to separate them into two vectors such that 'vector 1' contains the roots that are positive real, positive imaginary, and if complex - the complex number which has real positive part (irrespective of the sign on the imaginary part). The remaining roots will be in the second vector 'vector 2'. Thus each vector will usually contain four elements.
I have tried this so far,
vector1 = solve(eqn);
vector1(real(vector1)<0)=[ ]; % removes negative real roots
vector1(imag(vector1)<0)=[ ]; % removes negative imaginary roots
The problem is that the command to remove the imaginary roots also removes the complex roots with positive real part and negative imaginary part i.e. a-bi, but I want to keep those. I have thought about using an 'if' statement to say that if the number is complex then only remove the complex numbers with negative real part, but I haven't managed it.
Any advice would be awesome.
EDIT:
I managed to do it like this
eqn1=solve(eqn);
zimpos=[]; % to add the positive imaginary values
for k = [1:length(eqn1)]
if real(eqn1(k))==0;
zimpos=[zimpos,(imag(eqn1(k)))];
zimpos(zimpos>0)=[];
end
end
zimpos=zimpos*i;
zrealpos=[]; % to add the complex or real numbers with positive real part
for k= [1:length(eqn1)]
if real(eqn1(k))>0;
zrealpos=[zrealpos,(eqn1(k))];
end
end
zpos=[zrealpos zimpos]; % the final vector.
If anyone has any suggestions on improving this I would be very grateful.
Thanks.

采纳的回答

Jan
Jan 2013-10-7
eqn1 = solve(eqn);
hasImag = any(imag(eqn1(:))); % ~ISREAL might be wrong
m1 = ~hasImag & real(eqn1) > 0; % positive real
m2 = real(eqn1) == 0 & imag(eqn1) > 0; % positive imaginary
m3 = hasImag & real(eqn1) > 0; % complex and real positive part
m = m1 | m2 | m3;
vector1 = eqn1(m);
vector2 = eqn1(~m);
  1 个评论
AllKindsofMath AllKinds
Worked like a charm thank you very much. The only edit I made was that I needed to sort the roots so instead of the last two lines I did
vector1 = sort(eqn1(m)); vector2 = sort(eqn1(m))*-1;
Again thanks.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Monte Carlo Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by