I've got the following code for the first few terms of an expansion. I want to collect the terms in increasing powers of (s/r) but using an iterator. The code is as follows:

formula=1-n x + 1/2 n (n+1) x^2-1/6 n (n+1 ) (n+2) x^3 /. {x->((s/r)^2-2 (s/r) Cos[θ]),

The output is what I want but how would I do this using a counter or iterator? So something like

Collect[%, {(s/r)^i,{i,0,n}}]

But obviously not that because it doesn't work!

  • 1
    $\begingroup$ Could you just preinitialize your list of factors? E.g. Collect[Expand[formula], Table[(s/r)^i, {i, 5}]] $\endgroup$ – b3m2a1 Mar 9 '17 at 1:44
  • $\begingroup$ Excellent job. I had tried something almost the same but your has worked a treat! If you want to write it as an answer I shall kindly accept! $\endgroup$ – Rumplestillskin Mar 9 '17 at 1:54

We can pre-initialize our list of factors with Table:

Collect[Expand[formula], Table[(s/r)^i, {i, 5}]]

should get the job done.

Or, as Bob Hanlon notes, Power is Listable so we can do:

Collect[Expand[formula], (s/r)^Range[5]]
  • $\begingroup$ Ah very nice. Didn't know Power was Listable. $\endgroup$ – b3m2a1 Mar 9 '17 at 3:16

Instead of Collect, you can use PolynomialReduce

Flatten@PolynomialReduce[formula, Table[(s/r)^i, {i, n /. n -> 5}], {s, r}][[2]]

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.