use horner function in matlab

To use Horner's method in MATLAB for polynomial evaluation, you can define a MATLAB function that takes the coefficients of the polynomial as an input and then use the built-in function polyval to evaluate the polynomial.

Here is an example of how to use Horner's method in MATLAB:

main.m
function result = horner_evaluation(coefficients, x)
    % The coefficients array should be given in descending order, i.e., 
    % [a_n, a_(n-1), ..., a_1, a_0].
    % x is the value of x at which the polynomial is evaluated.
    
    % Get the degree of the polynomial
    degree = length(coefficients) - 1;

    % Initialize the result with the coefficient of the highest power of x
    result = coefficients(1);

    % Apply Horner's method to evaluate the polynomial
    for i = 2:length(coefficients)
        result = result * x + coefficients(i);
    end
end
566 chars
17 lines

Once you have defined the above function, you can call it by passing the coefficients of the polynomial and the value of x at which you want to evaluate the polynomial. For example:

main.m
coefficients = [3, -2, 0, 1]; % Polynomial: 3x^3 - 2x^2 + 1
x = 2;
result = horner_evaluation(coefficients, x);
112 chars
4 lines

The result variable will store the evaluated value of the polynomial at x.

Note that MATLAB has a built-in function called polyval that can be used for polynomial evaluation, so you don't necessarily have to implement Horner's method from scratch. Here is an example of using polyval for polynomial evaluation:

main.m
coefficients = [3, -2, 0, 1]; % Polynomial: 3x^3 - 2x^2 + 1
x = 2;
result = polyval(coefficients, x);
102 chars
4 lines

Both approaches will give you the same result.

gistlibby LogSnag