You are on page 1of 11

DEVELOPING FUNCTIONS IN MATLAB

 Function in MATLAB is always written in m-file. (Go to File->New->Blank m-file)

 Syntax:
function [out1, out2, …,outN] = fun_name (in1,in2, …,inM)
coding
end

 Above defines a function ‘fun_name’ that accepts inputs in1, in2, …,inM & returns
outputs out1, out2…,outN.

 Save the m-file with the same name as fun_name.

 Function is called in the command window using the name of the function.

 Valid function names begin with an alphabetic character, and can contain letters,
numbers, or underscores
INPUT AND OUTPUT PARAMETERS
 The input & output variables can be scalars, vectors, matrices and strings.

 MATLAB does not really distinguish between variables types until some
calculation or operation involving the variables is performed.

 e.g. y=sin(x)
 If ‘x’ is a scalar, ‘y’ is also a scalar.
 If ‘x’ is a vector, ‘y’ is also a vector.
 If ‘x’ is a matrix, ‘y’ is also a matrix.
FUNCTION EXAMPLE: ONE OUTPUT

function called in command window m-file(script file) saved as ‘average.m’


FUNCTION EXAMPLE: TWO OUTPTUS

function called in command window m-file(script file) saved as ‘stat.m’


FUNCTION EXAMPLE: CALLED IN A SCRIPT
FILE

Yplusxoutput called in command window m-file(script file) saved as ‘yplusx.m’

Another m-file(script file) saved as ‘yplusxoutput’


SUB-FUNCTION
 Function used within a function.

 Syntax:
function [out1, out2, …] = fun1 (in1,in2, …)
coding (fun2 used in coding)
end
function [out1, out2, …] = fun2 (in1,in2, …)
coding
end

 Above defines a function ‘fun1’ that accepts inputs in1, in2, … & returns
outputs out1, out2,… and also using fun2.

 The name of the variables in ‘fun2’ can be same as ‘fun1’ because ‘fun2’ will
work on a different space than ‘fun1’

 Save the m-file with the same name as ‘fun1’.


SUB-FUNCTION (EXAMPLE)
‘disp’ and ‘strcmp’ command
PLOTTING IN MATLAB
 MATLAB supports the 2D and 3D plotting of functions.
 The most basic command is plot(array).
 A commonly used syntax is plot(quantity on x-axis, quantity on y-axis).
 Coding example:
t=0:0.01:2;
x = cos(2*pi*4*t);
plot(t,x);
xlabel('time');
ylabel('amplitude');
title('plots');
PLOTTING IN MATLAB

(x(8),y(8))

(x(2),y(2))
Function with ‘plot’ command

You might also like