Kindly help me understand this code, it is a user defined function for multiplying two polynomials
显示 更早的评论
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 个评论
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.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Polynomials 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!