I have a vector u, with elements u[1],u[2],...u[n].

I then have an expression with terms that are linear in u[1],u[2],...u[n].

How can I collect these terms and group them as coefficients of u[1],u[2],...,u[n] without me having to explicitly state what n is?

When the collecting is actually done, n will be known, but I want to keep n arbitrary up to that point, and so need a method that works whichever value of n I pick.

New Issue: Similar to the above, but now for an input n, I have n^2 variables uu[1,1],...uu[1,n],...,[n,1],...,uu[n,n]. I want to cllect terms according to these variables. I've tried doing what I did before, writing down Array[uu,{n+1,n+1}], but this isn't working.

  • $\begingroup$ Don't worry, I figured it out. I needed to put Array[u,n] as the terms to collect, rather than just u (where u was previously defined by Array[u,n]). $\endgroup$
    – user112495
    Dec 11, 2019 at 14:01
  • $\begingroup$ Could somoene help with the extra bit added on now? $\endgroup$
    – user112495
    Dec 11, 2019 at 15:14

1 Answer 1


Maybe something along these lines:

Here's an expression linear in u[_]. I am assuming that some u[_] is actually present in the expression.

expr = 10 u[1] + 8 u[4];

Extract all variables (treating the expression as a polynomial), select those that match u[_], and find the largest index.

maxIndex = Cases[Variables[expr], _u][[All, 1]] // Max
(* 4 *)

Construct the variables u[1], u[2], ..., u[maxIndex], and extract their coefficients.

Coefficient[expr, u /@ Range[maxIndex]]
(* {10, 0, 0, 8} *)
  • $\begingroup$ Could I extend this to having a matrix of variables u[i,j] (in fact, u is actually only a tridiagonal matrix) without having to manually move the elements into a list? $\endgroup$
    – user112495
    Dec 11, 2019 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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