0
$\begingroup$

Suppose I have a list of pairs of complex numbers with nesting as follows

{
{{1.91885 + 0.09170475 I, 1.91901 + 0.0629745061 I},
 {1.91837 + 0.092182 I, 1.9189 + 0.063 I},
 {1.9837 + 0.2182 I, 1.99 + 0.063 I},
 {1.91837 + 0.0921 I, 1.89 + 0.3 I}},
 {{1.91 + 0.091 I, 1.91 + 0.062974 I},
  {1.918 + 0.092 I, 1.89 + 0.63 I},
  {1.915 + 0.0915 I, 1.9191 + 0.05061 I}
 }
}

In reality, the list I am working with has many more sublists (here I've just shown two) and many more elements in each sublist.

I am trying to extract the second component of each pair of complex numbers while maintaining the nesting so here the expected output would be

{{1.91901 + 0.0629745061 I, 1.9189 + 0.063 I, 1.99 + 0.063 I,1.89 + 0.3 I},
 {1.91 + 0.062974 I, 1.89 + 0.63 I,  1.9191 + 0.05061 I}}

I have tried defining a function sec[z_]:=Part[z,2] and using Map or Apply to get what I want but this doesn't seem to work. Is there a way to do this?

$\endgroup$
1
2
$\begingroup$

Try this:

lst = {{{1.91885 + 0.09170475 I, 
    1.91901 + 0.0629745061 I}, {1.91837 + 0.092182 I, 
    1.9189 + 0.063 I}, {1.9837 + 0.2182 I, 
    1.99 + 0.063 I}, {1.91837 + 0.0921 I, 
    1.89 + 0.3 I}}, {{1.91 + 0.091 I, 
    1.91 + 0.062974 I}, {1.918 + 0.092 I, 
    1.89 + 0.63 I}, {1.915 + 0.0915 I, 1.9191 + 0.05061 I}}};

Map[ReplaceAll[#, {x_, y_} -> y] &, lst]

(*  {{1.91901 + 0.0629745 I, 1.9189 + 0.063 I, 1.99 + 0.063 I, 
  1.89 + 0.3 I}, {1.91 + 0.062974 I, 1.89 + 0.63 I, 
  1.9191 + 0.05061 I}}   *)

Have fun!

$\endgroup$
1
  • $\begingroup$ Thanks Alexei! I always forget about using ReplaceAll. $\endgroup$ – math Nov 4 '20 at 10:58
1
$\begingroup$

Here is simpler way to do it with ReplacePart. No need to use Map. Like so:

ReplacePart[lst, {i_, j_} :> lst[[i, j, 2]]]
{{1.91901 + 0.0629745061 I, 1.9189 + 0.063 I, 1.99 + 0.063 I, 1.89 + 0.3 I}, 
 {1.91 + 0.062974 I, 1.89 + 0.63 I, 1.9191 + 0.05061 I}}
$\endgroup$
2
  • $\begingroup$ I ran some AbsoluteTiming experiments using this method and Alexei's. I found on my sample list Alexei's method took around 950 seconds, but ReplacePart didn't finish running even after letting it run for around a day. Are there some limitation with the ReplacePart method to be aware of? $\endgroup$ – math Nov 10 '20 at 9:33
  • $\begingroup$ @math. I don't have any idea why ReplacePart is running so slowly on your system. You don't describe your test in sufficient detail. I timed my code on this array: data = With[{rows = 1000, cols = 1000}, RandomComplex[1 + I, {rows, cols, 2}]]; and it completed in 2.3 sec. That seems pretty fact to me. $\endgroup$ – m_goldberg Nov 11 '20 at 7:59
1
$\begingroup$

Just this,

l //. {a___, {b_, c_}, d___} :> {a, c, d}

Where l is your list.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.