Friday, September 18, 2015

Matlab Tutorial Part 4 - Scripts and Functions

In Matlab we have the possibility to create scripts and functions containing often used code, helping us to not having to type it frequently.
The scripts and functions are saved in files with the ending .m. Scripts are simply collections of lines of code, whereas functions have some return value.
We can edit these files conveniently out of Matlab: For that we edit the command edit Name.m and confirm. Then an editor opens with this file.
As an example we create the script MyScript.m with the following content:

A = rand(100);
d = det(A)

So a random 100 x 100 matrix A is created and the determinant d calculated. In Matlab we can call this script by entering the name MyScript. Then the script is executed and the variable d outputted. What is outputted we can control via the character ";". If we end one line with a semicolon, it is executed without output. If we omit it, the result of the operation is outputted. So if we remove the semicolon in the first line of the script, the complete matrix is displayed as well.

As a second example we now create a function which calculates and returns the average over the given values. For this we enter edit MyFunction.m.
As content we input:

function [y] = MyFunction(x)
y = sum(x);
y = y / numel(x);
end

As one can see a function declaration starts with the keyword function and ends with end. In square brackets we first list the return values - here only y is returned, multiple parameters are simply separated by comma. After the equal sign we write the name of the function (which should coincide with the file name) as well as the input parameters in round brackets - here only x.
In the function we then sum over x (thus we expect a vector) and then divide this by the number of elements in x. The result is then returned by the function in y. In Matlab we then can call the function and use the return value as follows: test = MyFunction([1,2,3,])
(Note: In Matlab of course the average value can be calculated easier - for example via the predefined function mean(). I only chose this example for explanation.)

No comments:

Post a Comment