Effacer les filtres
Effacer les filtres

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

4 vues (au cours des 30 derniers jours)
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.

Réponse acceptée

Jan
Jan le 7 Oct 2013
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 commentaire
AllKindsofMath AllKinds
AllKindsofMath AllKinds le 12 Oct 2013
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by