Kindly help me understand this code, it is a user defined function for multiplying two polynomials

17 次查看(过去 30 天)
User-defined function:
p1 = [2 5 3];
p2 = [4 0 5 8 12];
p = polymult(p1,p2)
p = 1×7
8 20 22 41 79 84 36
p_matlab = conv(p1,p2)
p_matlab = 1×7
8 20 22 41 79 84 36
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 个评论
John D'Errico
John D'Errico 2023-8-25
编辑:John D'Errico 2023-8-25
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.

请先登录,再进行评论。

采纳的回答

John D'Errico
John D'Errico 2023-8-25
编辑:John D'Errico 2023-8-25
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)
p12 = 1×7
8 20 22 41 79 84 36
pconv = conv(p1,p2)
pconv = 1×7
8 20 22 41 79 84 36
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 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Polynomials 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by