【问题标题】:MatLab: Code for a sparse version of Horner's ruleMatLab:霍纳规则的稀疏版本的代码
【发布时间】:2013-12-04 01:22:45
【问题描述】:

我已经编写了计算多项式的代码

p(x)=a_0+x(a_1+x(a_2+x(a_3+...+x(a_(n-1)+xa_n)...)))
使用霍纳规则如下

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

我现在正在尝试为这个 ie 的稀疏版本编写代码

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。我可以在哪里找到这个的任何想法?我不确定如何自己编写代码。

【问题讨论】:

    标签: matlab


    【解决方案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)

    【讨论】:

    • 感谢您的帮助。我的问题中 p(x) 的公式是我被赋予工作的公式。我确定我需要我的输入是 Sparse(index,b,x) 我已经写了以下内容,但我认为它有一个错误function [answer] = Sparse(index,b,x) n=length(index); m=length(b); if(m~=n) error('The length of the vector b must be equal to that of index') end indicies=index(n)-index(n-1); result=b(m-1)+b(m)*myexpt(x,indicies); for j=m-2:-1:1 result=b(j)+myexpt(x,indicies)*result; end answer=result; end myexpt 是一个单独的函数来评估 x 某物的力量跨度>
    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 2012-06-20
    • 2020-12-12
    • 2012-01-03
    相关资源
    最近更新 更多