How to extract a coefficient from a sum

Let us consider a sum of specified functions multiplied by coefficients, for example

f[x_]:= Sum[Exp[j*x]*p[j],{j,1,n}]

I want to extract the coefficient corresponding to the n-th term, which is

p[n].

How can I do it? Thanks Giulia

• Can you add a simple example? – Moo Nov 21 '18 at 13:49
• Assuming s = Sum[Exp[j*x]*p[j], {j, 1, 10}]; try this Coefficient[s, E^(5 x)]. Is it what you need? – Alexei Boulbitch Nov 21 '18 at 14:33
• No, because in my case I do not want to define n In your example n = 10 and I do not want to define it – Giulia Bevilacqua Nov 21 '18 at 14:35
• I'm not understanding the question. Here's why: For the example you give it is explicitly known that the coefficient is p[n]. Why not just say that the coefficient is p[n] ? Is your real example more complicated where the coefficient isn't so obvious? – JimB Nov 21 '18 at 14:48
• No, it is not my real problem. This example is just a simplification of what I have to do. here the coefficient is simply p[n], but in my real problem it is the result of other previous computations. – Giulia Bevilacqua Nov 21 '18 at 15:41

Perhaps this:

sum = Sum[Exp[j*x]*p[j], {j, 1, n}];
basis = Exp[j*x];
index = n;
sum /. {
HoldPattern@Sum[term_, {idx_Symbol, i0_: 1, i1_}] /;
Not@ TrueQ@ Not@ Simplify[i0 <= index <= i1, index ∈ Integers] :>
Block[{idx = index}, Coefficient[term, basis]],
_ -> 0}

(*  p[n]  *)

The Not@ TrueQ@ Not@... tries to check that index is not provably out of range (e.g. index = n + 1 returns a coefficient of 0, but index = k returns p[k]).