使用Euclid和Horner算法的多项式求值

时间:2019-12-05 14:24:52

标签: matlab polynomials

我正在编写这段代码来评估图像中的多项式1

我的代码是

function [px] = HornerEuclid(index,b,x)
%write a function HornerEuclid which evaluates a
%polynomial using the improved sparse Horner scheme. implementing
%previously defined functions PolyEuclid, HornerSparse and FastPower
g=PolyEuclid(index);
y=FastPower(x,g);
k=length(index);
if ~isempty(index)
while g~=0
    for j=1:k
    index(j)=index(j)/g;
    end
    break
end 
    px=HornerSparse(index,b,y);
elseif isinteger(x)
    px=[0];
else 
     px=(zeros(size(x)));
end 

HornerSparse的代码是

function [px] =HornerSparse(index,b,x)
%evaluates a polynomial p(x) using the Horner scheme given
%in Eq. (3).
%The function should return the value of the polynomial for a given x 
%and lists i, b.
if isinteger(x) || ismatrix(x)
    if ~isempty(b) &&  ~isempty(index)
        k=length(b);
        if k>1
        px=b(k)*eye(size(x));
        for j=k:-1:2
            px= b(j-1)*eye(size(x))+ px*FastPower(x,index(j)-index(j-1));
        end
        else
            px=b(k)*FastPower(x,index(k));
        end
    elseif isinteger (x)
       px=[0];
    else
        px=(zeros(size(x)));
    end
else 
    error('input values must be integers or square matrices')
end

并且PolyEuclid的代码是

function [gcd] = PolyEuclid(r)
%calculates the greatest common divisor of a list r =[r1, r2, . . . , rm] 
%of n integer numbers using Algorithm 2. 
gcd=r(1);
for j=2:length(r)
    gcd=Euclid(gcd,r(j));
end

使用另一个函数Euclid查找2个数字的gcd,而FastPower(x,n)查找x ^ n。

测试图像2中显示的HornerEuclid代码时,出现以下错误消息,但我不知道如何解决。 HornerSparse和PolyEuclid这两个代码都是正确的。

0 个答案:

没有答案