1

I'm looking for a built-in Matlab function that sums two polynomial.

Example:

\ p_1(x) = 500x^5 + 400x^4 + 300x^3 + 200x^2 + 100x + 50 \ p_2(x) = \qquad\qquad\qquad\qquad\;\, 3x^3 + \quad 2x^2 + \quad\;\, x + \;\; 5 \ p_s(x) = 500x^5 + 400x^4 + 303x^3 + 202x^2 + 101x + 55

p1(x) and p2(x) are represented in code standard Matlab vectors:

p1 = [500 400 300 200 100 50];
p2 = [3 2 1 5];

How do I sum these two polynomials to get ps(x) with using built-in Matlab function(s); without writing an explicit m-file function?

hkBattousai
  • 10,583
  • 18
  • 76
  • 124

4 Answers4

4

Simple. Write a little function, call it leftpadz.

leftpadz = @(p1,p2) [zeros(1,max(0,numel(p2) - numel(p1)))),p1];

So if we have...

p1 = [500 400 300 200 100 50];
p2 = [3 2 1 5];
p3 = leftpadz(p1,p2) + leftpadz(p2,p1)
p3 =
   500   400   303   202   101    55
3

I sure hope there is a nicer way of doing it (I'd probably put this into a helper function), but this seems to work just fine:

[zeros(1, size(p1,2)-size(p2,2)) p2] + [zeros(1, size(p2,2)-size(p1,2)) p1]

ans =

   500   400   303   202   101    55
Christopher Creutzig
  • 8,656
  • 35
  • 45
2
function c = polyadd( a, b)
assert( isrow(a))
assert( isrow(b))

maxL = max( [length(a), length(b)]);
a = [ zeros( 1, maxL - length(a)), a];
b = [ zeros( 1, maxL - length(b)), b];

c = a +b ;
end
Andronicus
  • 25,419
  • 17
  • 47
  • 88
0

Have you tried this:

p1 = [500 400 300 200 100 50];
p2 = [0 0 3 2 1 5]; # refilling with 0

ps = p1 + p2;