# Collect terms according to elements of a vector

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

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

How can I collect these terms and group them as coefficients of u,u,...,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.

• 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]). Dec 11, 2019 at 14:01
• Could somoene help with the extra bit added on now? Dec 11, 2019 at 15:14

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 + 8 u;


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, u, ..., u[maxIndex], and extract their coefficients.

Coefficient[expr, u /@ Range[maxIndex]]
(* {10, 0, 0, 8} *)

• 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? Dec 11, 2019 at 15:23