How to write M-files in MATLAB.

Normally, when single line commands are entered, MATLAB processes the commands immediately and displays the results. MATLAB is also capable of processing a sequence of commands that are stored in files with extension m. MATLAB files with extension m are called m-files.
Function files are m-files that are used to create new MATLAB functions.Variables defined and manipulated inside a function file are local to the function, and they do not operate globally on the workspace. However, arguments may be passed into and out of a function file.


The general form of a function file is
function variable(s) = function_name (arguments)

% help text in the usage of the function

%


.


.


end

Example: Write a MATLAB function to obtain roots of the quadratic equation ax2 + bx + c = 0 ?
function rt = rt_quad(coef)
%
% rt_quad is a function for obtaining the roots of
% of a quadratic equation
% usage: rt = rt_quad(coef)
% coef is the coefficients a,b,c of the quadratic
% equation ax*x + bx + c =0
% rt are the roots, vector of length 2
% coefficient a, b, c are obtained from vector coef



a = coef(1); b = coef(2); c = coef(3);
int = b^2 - 4*a*c;
if int > 0
srint = sqrt(int);
x1= (-b + srint)/(2*a);
x2= (-b - srint)/(2*a);
elseif int == 0
x1= -b/(2*a);
x2= x1;
elseif int < 0
srint = sqrt(-int);
p1 = -b/(2*a);
p2 = srint/(2*a);
x1 = p1+p2*j;
x2 = p1-p2*j;
end
rt =[x1;
x2];
end

The above MATLAB script can be found in the function file rt_quad.m.

We can use m-file function, rt_quad, to find the roots of the following quadratic equations:
(a) x2 + 3x + 2 = 0
(b) x2 + 2x + 1 = 0
(c) x2 -2x +3 = 0

The following statements, that can be found in the m-file ex1_4.m, can be used to obtain the roots:

ca = [1 3 2];

ra = rt_quad(ca)

cb = [1 2 1];

rb = rt_quad(cb)

cc = [1 -2 3];

rc = rt_quad(cc)

The following results will be obtained:

ra =
-1
-2

rb =
-1
-1

rc=
1.0000 + 1.4142i
1.0000 - 1.4142i