Functions in MATLAB

Declaring a function file

To solve the function y = 3x2 - e-x for arbitrary values of x, create a function file by selecting New from the File menu. Into the window, type the following statements:

function z = foo (x)

z = 3*x  .*  x - exp(-x);

Save the file by choosing Close, clicking on the Close Window box, or simply choose Save from the File menu.

Use the function to compute 3x2 - e-x for x = 1;

    >> foo(1)


Compute 3x2 - e-x for x = 3 and store it into variable m;

    >> m = foo(3)
 
 

Compute 3x2 - e-x for x = 3t2 - e-t when t = 2;

>> t = 2; foo(foo(t))
 
 

Solving roots of polynomials

Define the coefficients of a 2nd order polynomial as an array. Take for example, the polynomial 2x2 + 3x + 4 = 0.

>> p = [ 2 3 4 ]

Solve for the roots of the polynomial p:

>>  roots(p)