Section 9.5 Adding Polynomials
Adding polynomials is easy: you simply add terms of equal powers of x:
\begin{equation*}
p_1(x) = x^2 - 3x + 1, \text{ } p_2(x) = 3x^2 + 2
\end{equation*}
Then, if \(p = p_1 + p_2\text{,}\) we have
\begin{equation*}
p(x) = 4x^2 - 3x + 3
\end{equation*}
In MATLAB you thus simply add the corresponding vectors of coefficients:
>> p1 = [1 -3 1]; >> p2 = [3 0 2]; >> p = p1 + p2
p = 4 -3 2
The only thing you have to watch out for is polynomials of different orders. You must pad the lower order polynomial with zeros before adding them together since otherwise the vectors of coefficients wouldn’t have the same length. Take a look:
\begin{equation*}
p_1(x) = x^2 - 3x + 1, \text{ } p_2(x) = x
\end{equation*}
Then, if \(p = p_1 + p_2\text{,}\) we have
\begin{equation*}
p(x) = x^2 - 2x + 1
\end{equation*}
Without padding the second polynomial this is what happens in MATLAB:
>> p1 = [1 -3 1]; >> p2 = [1 0]; >> p = p1 + p2
\(\color{red}{\text{Matrix dimensions must agree.}}\)
Instead, pad the vector p2 so that it has the same length as the vector p1:
>> p1 = [1 -3 1]; >> p2 = [0 1 0]; >> p = p1 + p2
p = 1 -2 1