MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

# Get coeffients of symbolic expression

Asked by Mech Princess on 21 Jul 2012

I have a set of equations (derv_alpha) that I have arrived at by differentiating an expression and setting it to zero.

```N=3; alphavec = sym('alpha',[1 N]); %N can take any value
derv_alpha = [ 0, 2*alphavec(3) - 2*alphavec(2) + 2, 2*alphavec(2) - 4*alphavec(3)];
```

Now I need to solve these simultaneous equations and come up with answers for alpha2, alpha3...alphaN. i.e. alphavec(2), alphavec(3)...alphavec(N).

I am trying to put this in matrix form A*x=b and solve for x. Is it possible? If so, HOW CAN I GET THE COEFFICIENTS OF EACH VARIABLE?

The solution will have to be irrespective of the position of the variable in the expression.

I did a quick search. collect() doesnt work. i dont think sym2poly can be used

OR, is there a better way to do it when working with symbols?

I am doing my first program using symbols this week and appreciate any help. Thanks again.

## Products

No products are associated with this question.

Answer by Walter Roberson on 21 Jul 2012

Generally,

```solve(derv_alpha, alphavec)
```

However, derv_alpha(1) is the constant 0 and not an expression in the alpha variables, so the set of three equations in derv_alpha, in three variables, is really only two equations in three variables, which you aren't going to be able to solve for. This is going to be a problem even if you express as A*x=b

Walter Roberson on 21 Jul 2012

```derv_alpha = [2*alphavec(3) -2*alphavec(2) + 2, 2*alphavec(2) -4*alphavec(3)];
```

with no space after the '-', then the '-' would be interpreted as unary minus and the space would be interpreted as the end of the term in the list. [A - B] is one expression but [A -B] is two, A and -B . You can ensure your desired groupings by adding ()

Mech Princess on 21 Jul 2012

Thanks. It's an output from another line of code which is the partial derivative of an expression. The spaces are what MATLAB gives and frankly, I was wondering about it myself. Thanks

Mech Princess on 21 Jul 2012

does anyone know how to do this? Thanks