Polynomials and Functions

Created

Polynomails and Functions


Functions should be a well-defined and contained sub-program.

Arguments

Input and ouput arguments are optional. When there is only one output argument you can omit the brackets: function x = divby(a, b, c)

Create a function with an optional number of input and output arguments by using

  • nargin - returns the number of actual inputs
  • nargout - returns the number of actual outputs.
  • narginchk(min, max) - checks that the number of input arguments is in the allowable range.
  • nargoutchk(min, max) - checks that the number of output arguments is in the allowable range.

Example usage:

function x = divby(a, b, c)
	narginchk(1,3)

	if nargin < 2 b = a;
	if nargin < 3 c = 1;
	x=1./(a:c:b);
end

Anonymous Function

Construct simple functions without the need to create an M-File on the command line or within a script/function:

Function_name=@(argslist) expr

% examples:
sq = @(x) x^2;
poly1 = @(x) 4*x.^2 - 50*x + 5;

eval and feval

eval(string) evaluates a character string as though it has been typed in the command window. Example:

x = eval('sin(pi/4)')

feval(fun, value) ervalues a named functino at a specific input value.

x = feval('sin', pi/4)

Polynomials

Addition Adding two polynomials requires adding their coefficients. In a row-vector representation, add them element-by-element. Make sure the coefficients add up by adding leading zeros.

function C = addpoly(A, B)
lenA = length(A);
lenB = length(B);

if lenA == lenB
	C = A+B
elseif lenA < lenB
	C =[zeros(1, lenB-lenA) A] + B;
else 
	C =A + [zeros(1, lenA-lenB) B]
end

Subtraction

function C = subpoly(A, B)
C = addpoly(A, -B)

Multiplication To multiply two poloynomials, you need a loop

function C = multpoly(A, B)
lenA = length(A);
lenB = length(B);
lenC = lenA + lenB - 1;

C = zeros(1, lenC);
for i = 1:1:lenB
	idx = i:i+lenA-1
		C(idx) = A*B(i) + C(idx);
end

Evaluation polyval works for vectors

Roots The command roots computes the roots of a polynomial and returns them as a column vector.