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 = 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

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.

댓글을 달려면 로그인하십시오.

 채택된 답변

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

The question actually is,write a user defined function that multiplies two polynomials,function name,p=polymult(p1,p2) The input arguments p1 and p2 are vectors of coefficients of the two polynomials.The output argument is the resulting polynomial.
So let me see. I did write exactly that, no? Is that not true?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Polynomials에 대해 자세히 알아보기

질문:

2023년 8월 25일

댓글:

2023년 8월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by