Accelerating the pace of engineering and science

# collect

Collect coefficients

## Description

example

collect(P) rewrites P in terms of the powers of the default variable determined by symvar.

example

collect(P,var) rewrites P in terms of the powers of the variable var. If P is a vector or matrix, this syntax regards each element of P as a polynomial in var.

## Examples

### Collect Coefficients in Terms of the Powers of a Default Variable

Collect the coefficients of this symbolic expression:

```syms x
collect((exp(x) + x)*(x + 2))```
```ans =
x^2 + (exp(x) + 2)*x + 2*exp(x)```

Because you did not specify the variable of a polynomial, collect uses the default variable defined by symvar. For this expression, the default variable is x:

`symvar((exp(x) + x)*(x + 2), 1)`
```ans =
x```

### Collect Coefficients in Terms of the Powers of a Particular Variable

Rewrite this symbolic expression specifying the variables in terms of which you want to collect the coefficients:

```syms x y
collect(x^2*y + y*x - x^2 - 2*x, x)
collect(x^2*y + y*x - x^2 - 2*x, y)```
```ans =
(y - 1)*x^2 + (y - 2)*x

ans =
(x^2 + x)*y - x^2 - 2*x```

### Collect Coefficients in Terms of the Powers of i and pi

Rewrite these expressions in terms of the powers of i and pi, respectively:

```syms x y
collect(2*x*i - 3*i*y, i)
collect(x*pi*(pi - y) + x*(pi + i) + 3*pi*y, pi)```
```ans =
(2*x - 3*y)*i

ans =
x*pi^2 + (x + 3*y - x*y)*pi + x*i```

### Collect Coefficients for Each Element of a Matrix

If the argument is a vector or a matrix, then collect rewrites each element:

```syms x y
collect([(x + 1)*(y + 1), x^2 + x*(x -y); 2*x*y - x, x*y + x/y], x)```
```ans =
[ (y + 1)*x + y + 1, 2*x^2 - y*x]
[       (2*y - 1)*x, (y + 1/y)*x]```

## Input Arguments

expand all

### P — Input expressionsymbolic expression | symbolic function | symbolic vector | symbolic matrix

Input expression, specified as a symbolic expression, function, vector, or matrix.

### var — Variable in terms of which you collect coefficientssymbolic variable | symbolic expression

Variable in terms of which you collect the coefficients, specified as a symbolic variable or symbolic expression, such as i or pi.