sorting a complex vector by imaginary part in R

后端 未结 2 1553
青春惊慌失措
青春惊慌失措 2021-01-23 14:11
roots <- polyroot(c(5, 4, 3, 2, 1))

I want to sort the roots by ascending order of the imaginary part. By default the sort function sor

相关标签:
2条回答
  • 2021-01-23 14:48

    Use Im function to extract the imaginary part and sort it.

    roots <- polyroot(c(5, 4, 3, 2, 1))
    #[1]  0.287815+1.416093i -1.287815+0.857897i -1.287815-0.857897i
    #[4]  0.287815-1.416093i
    
    roots[order(Im(roots))]
    #[1]  0.287815-1.416093i -1.287815-0.857897i -1.287815+0.857897i
    #[4]  0.287815+1.416093i
    
    0 讨论(0)
  • 2021-01-23 14:59

    This also works:

    > roots<-polyroot(c(5,4,3,2,1))
    > roots[sort(Im(roots),index.return=T)$ix]
    [1]  0.287815-1.416093i -1.287815-0.857897i
    [3] -1.287815+0.857897i  0.287815+1.416093i
    

    Sort the complex numbers by their imaginary parts and return their indexes, then use the indexes to refer the corresponding complex value in the sorted order.

    0 讨论(0)
提交回复
热议问题