Kindly help me understand this code, it is a user defined function for multiplying two polynomials
16 views (last 30 days)
Show older comments
Tanui Redempter
on 25 Aug 2023
Commented: Tanui Redempter
on 25 Aug 2023
User-defined function:
p1 = [2 5 3];
p2 = [4 0 5 8 12];
p = polymult(p1,p2)
p_matlab = conv(p1,p2)
function p = polymult(p1,p2)
%Multiply polynomials
na=length(p1); nb=length(p2);
if nb > na d=p1; p1=p2;
clear b
p2=d; nd=na; na=nb; nb=nd;
end
for k=1:nb
p(k)=0;
for i=1:k
p(k)=p(k)+p1(i)*p2(k+1-i);
end
end
for k=nb+1:na
p(k)=0; for i=k-nb+1:k
p(k)=p(k)+p1(i)*p2(k+1-i);
end
end
for k=na+1:na+nb-1
p(k)=0; for i=k-nb+1:na
p(k)=p(k)+p1(i)*p2(k+1-i);
end
end
end
1 Comment
John D'Errico
on 25 Aug 2023
Edited: John D'Errico
on 25 Aug 2023
Are you asking why the user written code does the same thing as conv (though poorly written IMHO), for multiplying two polynomials? Are you asking how that godawful code works at all?
Note that a well written code to perform the multiply need use only one set of loops not three separate sets of loops. As well, a well written code would actually have more than one comment line, so as to be self-documenting. I could make a few more points in this. But if you got that code for free, then it is likely worth exactly what you paid for it: nothing.
Accepted Answer
John D'Errico
on 25 Aug 2023
Edited: John D'Errico
on 25 Aug 2023
I'm sorry, but that code is complete crapola. Better code might look something like that below.
Test it out.
p1 = [2 5 3];
p2 = [4 0 5 8 12];
p12 = polymult(p1,p2)
pconv = conv(p1,p2)
function pprod = polymult(P1,P2)
% simple polynomial multiply code
n1 = numel(P1); n2 = numel(P2);
% known length of the result
nprod = n1 + n2 - 1;
% pre-allocate final result as all zeros
pprod = zeros(1,nprod);
% single loop to perform the multiply, though it is actually
% an implicit double loop, since a scalar*vector multiply is employed
for i1 = 1:n1
ind = i1+(0:n2-1);
% just multiply every element of P1 with all of the elements of P2,
% and sum them up.
pprod(ind) = pprod(ind) + P1(i1)*P2;
end
end
Note that the explanation of why and how the code works is complete, and inside the code. I would expect that the use of conv would be faster, since conv will be compiled code.
4 Comments
John D'Errico
on 25 Aug 2023
Edited: John D'Errico
on 25 Aug 2023
So let me see. I did write exactly that, no? Is that not true?
More Answers (0)
See Also
Categories
Find more on Polynomials in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!