Miscellaneous tips for MATLAB

From LiteratePrograms

Jump to: navigation, search

Polynomials

Here is a simple function to compute the value of a polynomial function on a domain.

The polynomial coefficients are stored in a vector:

P = [1 2 3];

means:

P(X) = X2 + 2X + 3

and more generally:

simple_poly.m
function y = simple_poly(x, P)
y=(repmat(x(:),1,length(P)).^repmat(length(P)-1:-1:0,length(x),1)) * P(:);

or as an anonymous function:

f=@(x,a)((repmat(x(:),1,length(a)).^repmat(length(a)-1:-1:0,length(x),1)) * a(:))

External links

  • The MATLAB built-in polyval function
Download code
Views