Transcript Introduction to MATLAB
Introduction to MATLAB
session 2 Simon O’Keefe Non-Standard Computation Group [email protected]
Content
Writing scripts
Flow control
Writing and using functions
Using cell arrays
Creating structure arrays
Plotting data
2
1 Scripts
3
1 Scripts
Instead of typing each command into Matlab you can store them in a file known as a script To execute the commands in a script, type it’s name into the command prompt Within the script, you have access to variables defined in the workspace.
Comments are denoted using the % symbol. Anything written after % is ignored by Matlab mresult = mean(results) % calculate the mean of the data 4
1 Scripts
To create a new script you can use the edit command >> edit This can also be used to open an existing script >> edit script_name Save the script, the filename will be the name of the script To run the script type the name into the command prompt >> script_name 5
2 Flow control
6
2 Flow control
For command Use a for loop to repeat one or more statements The end keyword tells Matlab where the loop finishes You control the number of times a loop is repeated by defining the values taken by the index variable This uses the colon operator again, so index values do not need to be integer For example >> for i = 1:4 a(i) = i * 2 end 7
2 Flow control
The counter can be used to index different rows or columns E.g.
>> results = rand(10,3) >> for i = 1:3 m(i) = mean(results(:, i)) end ..although you could do this in one step m = mean(results); 8
2 Flow control
>> for i = 1:3 m(i) = mean(results(:, i)) end m( 1 ) = mean(results(:, 1 )) 9
2 Flow control
>> data = [4 14 6 11 3 14 8 17 17 12 10 18] >> cat = [1 3 2 1 2 2 3 1 3 2 3 1] To work out the mean for each category you could type 3 commands: >> mdata(1) = mean(data(cat == 1)) >> mdata(2) = mean(data(cat == 2)) >> mdata(3) = mean(data(cat == 3)) Which is OK when there are a few categories but any more would create a lot of work You can use a for loop instead >> for i = 1:3 mdata(i) = mean(data(cat == i)) end The variable mdata will consist of 3 elements containing the mean of the values in data. The first element will contain the mean for category 1, second element the mean for category 2 and so forth.
10
2 Flow control >> for i = 1:3 mdata(i) = mean(data(cat == i)) end
mdata( 2 ) = mean(data(cat == 2 )) 11
2 Flow control
The ‘ if ’ command is used with logical operators Again, the end command is used to tell Matlab where the statement ends.
For example, the following code loops through a matrix performing calculations on each column >> for i = 1:size(results, 2) m = results(:, i) if m > 1 end do something else end do something different 12
2 Flow control
13
2 Flow control
The ‘while’ command >> while statement commands end
Waiting
>> while mean(results) > 10 ind = results ~= max(results) results = results(ind) end
Reading
>> fid = fopen (‘results.txt'); fline = ‘’; while tline ~= -1 disp(tline) tline = fgetl(fid); end fclose(fid); 14
2 Flow control
We can use flow control to display results for each of several experiments on separate plots.
mresult = mean(results) for i = 1:3 figure plot(results(:, i), ‘b.-’) hold on plot([1:10], repmat(mresult(i), 1, 10), ‘r-’) hold off end 15
2 Flow control
If we use flow control in a script we do not know the size of the results matrix when it will be run.
Instead, we make the script more general: mresult = mean(results) for i = 1: size(results, 2) figure plot(results(:, i), ‘b.-’) hold on plot([1: size(results, 1) ], repmat(mresult(i), 1, size(results,1)), ‘r-’) hold off end 16
3 Functions
17
3 Functions
More functions: pca – calculates the principle components of a set of data fft – performs the fast Fourier transform on a data set var – calculates the variance of the data repmat – replicates a matrix numel – returns the number of elements in a vector (or matrix) cumsum – calculates the cumulative summation sort – sorts a vector into ascending order floor & ceil – rounds data values down or up to the nearest whole value A list of the core functions that are available is located in Matlab’s help section. (Help Menu -> Matlab Help, in the right part of the window there is a Functions link) 18
3 Functions >> sortrows(data, col)
19
3 Functions
Some functions can return two or more outputs.
If this is the case use the following command structure >> [output1, output2] = function_Name(input1) For example >> rows = size(results) Could be written: >> [rows, cols] = size(results) 20
3 Functions
To find out what outputs a function can return use the help command 21
3 Functions
>> [sdata, ind] = sortrows(data, col) 22
3 Functions
The function xlsread reads data from an Excel spreadsheet >> [num, text] = xlsread(filename, sheet, ‘range’) Only the filename parameter is required, the others are optional The text output is optional, if it is not used only the data from the spreadsheet is loaded 23
3 Functions
24
3 Functions
You can create your own function if you need to use some calculation that is not provided by Matlab.
This done in a similar way to creating a script; use the same edit command to edit a function.
>> edit function_Name 25
3 Functions
The flow of a function is the same as a script; commands are carried out in the order that they appear and loops can be used.
However, a function does not have access to variables in the workspace. Instead, you pass the data to the function. And once the function has finished it returns it’s results back to the output variable used when you called the function. Any variables you create within the function are deleted.
26
3 Functions
When writing a function the first line must always be in the form: function [outputvariable, outputvariable2] = function_Name(inputvariable1, inputvariable2) This line tells Matlab the name of the function and how it can be used The function name must match the file name The output variable must be assigned a value inside the function.
The input variables can be accessed inside the function using their names.
27
3 Functions
The function: function m = mymean(data) m = sum(data) ./ size(data, 1) Can be used in a script or at the command prompt using: >> cm = mymean(data) 28
4 Cell Arrays
29
4 Cell Arrays
Standard arrays hold 1 value per element which is ideal for storing results However, if you try to store a string, each letter is treated as a vector element For example >> str = ‘subject1’ [s, u, b, j, e, c, t, 1] >> str = [‘subject1’, ‘subject2’] [s, u, b, j, e, c, t, 1, s, u, b, j, e, c, t, 2] >> str(1) ‘s’ Strings can not be stored and organised easily in vectors or matrices Cell arrays allow you to do this 30
4 Cell Arrays
A cell array is similar to a normal array except that each cell can contain a whole array or vector (or a single value) And the item in each cell does not need to be the same size or even the same type Curly brackets are used to define cell arrays All other operations work the same as with a normal array except that you use curly brackets instead of round brackets For example: >> labels = {‘string1’, ‘string2’, ‘string3’} >> labels{1} ‘string1’ 31
5 Plots
32
5 Plots
Saving plots to a file >> print(fileformat, filename) file format: ‘-dbitmap’ ‘-depsc’ You can also achieve this using the File -> Save menu in the figure’s window The command line version is useful when you want to generate a lot of plots in a script which are saved automatically 33
5 Plots
>> for i = 1:numel(results) figure plot(results(i).data, ‘b.-’) hold on plot([1:size(results(i).data)], repmat(results(i).mdata), ‘r-’) end hold off print(‘-bmp’, [‘c:\users\tom\desktop\’, results(i).label]) 34
5 Plots
Subplots Multiple plots can be placed within the same window This is achieved using the subplot command The window is split into a grid the size of which is specified when entering the command >> subplot(2,2,1) This creates a grid 2 x 2 in size (4 plots) and sets the current plot to the first of these. 35
5 Plots
>> subplot(2,2,1) 1 3 2 4 36
5 Plots
>> figure cols = 4 rows = ceil(numel(results) / cols) for i = 1:numel(results) subplot(rows, cols, i) plot(results(i).data, ‘b.-’) hold on plot([1:size(results(i).data)], repmat(results(i).mdata), ‘r-’) hold off end 37
5 Plots
38
5 Plots
Handles allow you to create a plot and then edit the properties later.
A handle is created when you create a plot or an object within the plot (for example title, legend) >> h = plot(data) This returns a handle to the line/s plotted, now you can change the line style, colour, width etc.
The handle is stored in a variable which can then be used to edit the properties with the set command For example, the position of a plot’s legend can be changed using handles >> plot(data) >> h = legend('line') >> set(h,'Location','South') 39
5 Plots
Inside/outside Best/Bestoutside Northwest North Northeast West East Southwest South Southeast 40
5 Plots
Colour bars can be repositioned in the same way: >> h = colorbar >> set(h, ‘Location’, ‘North’) 41
5 Plots
The figure function also returns a handle, you can use the set function to change the figure title: >> h = figure >> set(h, 'Name', 'Subject1') 42
5 Plots
Surface plot >> surf(matrix) >> colorbar >> axis([1 50 1 50 0 1]) >> title('Surface Plot'); >> xlabel('x') >> ylabel('y') >> zlabel('z') 43
5 Plots
Contour >> contour(data) >> colorbar >> xlabel('x') >> ylabel('y') >> zlabel('z') >> title('Contour Plot'); >> axis([1 50 1 50]) 44
5 Plots
All of these can be use in conjunction with subplot, therefore, you can display several different plot types in one figure 45