我编写了用于评估多项式的代码
P(X)= A_0 + X(A_1 + X(A_2 + X(A_3 + ... + X(A_(N-1)+ xa_n)...)))
使用Horner的规则如下
function [answer ] = Simple( a,x )
%Simple takes two arguments that are in order and returns the value of the
%polynomial p(x). Simple is called by typing Simple(a,x)
% a is a row vector
%x is the associated scalar value
n=length(a);
result=a(n);
if (any(a~=floor(a))
error('The values in a must be integers')
end
for j=n-1:-1:1 %for loop working backwards through the vector a
result=x*result+a(j);
end
answer=result;
end
我现在正在尝试编写一个稀疏版本的代码,即
P(X)= X ^(I_1)(B_1 +的x ^((I_2) - (I_1))(B_2 +的x ^((I_3) - (I_2))(B_3 + ... + X ^( (I_(K-1)) - (I_(K-2)))(B_(K-1)+ X ^((I_K) - (I(K-1)))b_k)...)))
我认为我需要输入为i
的行向量和b的行向量以及标量值x
。我能找到的任何想法吗?我不确定如何自己编码。
答案 0 :(得分:1)
回答这个问题的一种方法是查看p(x)
中的中间词,
这将是
...(b_j + x^(i_(j+1) - i_j)(...
而不是通常的...(a_j + x(...
,因此您需要更改行result=x*result+a(j);
。
同样,p(x)
的公式中存在轻微缺陷,它应该是p(x) = x^(i_1 - 1)(...
,这来自p(x) = a_1 x^0 + a_2 x^1 + ... + a_n x^(n-1)
来自Matlab中矩阵索引的事实从1开始而不是0.这是完整的代码
function [answer ] = SparseHorner( a,x )
% SparseHorner takes two arguments that are in order and returns the value of the
% polynomial p(x). SparseHorner is called by typing SparseHorner(a,x)
% a is a sparse row vector
% x is the associated scalar value
%// Find the entries where a is nonzero
[xInd yInd aVal] = find(a);
if any(aVal~=floor(aVal))
error('The values in a must be integers')
end
%// a is a row vector so only yInd's values change
ind = yInd;
result=aVal(end);
%// for loop working backwards through the vector a
%// numel is better than length
for j=(numel(ind)-1):-1:1
%// a(ind(j)) is much slower than aVal(j)
result=x^(ind(j+1)-ind(j))*result + aVal(j);
end
answer=result*x^(ind(1)-1);
end
请注意,这与a
的处理方式不同于Matlab的polyval
,后者有p(x) = a_1 x^n + ... + a_n
;如果你想保持一致,那么在函数开头附近加上a = fliplr(a)
行。