playground_04_functions - VMinhoto/workshop-matlab GitHub Wiki
Functions
A function is a group of statements that together perform a task. In Matlab, functions are defined in separate files. The name of the file and of the function should be the same.
Functions can accept more than one input arguments and may return more than one output arguments.
Syntax of a function statement is − function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)
Example
This function, called mymax shoul be written in a file named mymax.m. It takes 5 numbers as input and returns the maximum.
function max = mymax(n1, n2, n3, n4, n5)
%This function calculates the maximum of the
% five numbers given as input
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end
end
Create the .m file and type the code into it.
If you type help mymax
the strings immediately after the function definition will appear.
You can call the function by typing, for example, maximum=mymax(2, 30, 100, 9, 11)
.
Try to predict the result then run it on your workspace.
Example with input error test
You might want to test if the numbers of inputs is correct. There is a very useful command called nargin
that returns the number of input arguments. Modify mymax example to look like this:
function max = mymax(n1, n2, n3, n4, n5)
%This function calculates the maximum of the
% five numbers given as input
if nargin~=5 %This test if number of inputs is different then 5
error('You have to input 5 numbers')
end
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end
end