Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group [email protected].
-
date post
21-Dec-2015 -
Category
Documents
-
view
221 -
download
2
Transcript of Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group [email protected].
![Page 2: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/2.jpg)
Content Writing scripts Flow control Writing and using functions Using cell arrays Creating structure arrays Plotting data
2
![Page 3: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/3.jpg)
1 Scripts
3
![Page 4: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/4.jpg)
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
![Page 5: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/5.jpg)
1 Scripts
5
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
![Page 6: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/6.jpg)
2 Flow control
6
![Page 7: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/7.jpg)
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
![Page 8: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/8.jpg)
2 Flow controlThe 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
![Page 9: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/9.jpg)
m(2) = mean(results(:, 2))m(3) = mean(results(:, 3))
i = 2i = 3
2 Flow control
>> for i = 1:3
m(i) = mean(results(:, i))
end
9
i = 1
m(1) = mean(results(:, 1))
![Page 10: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/10.jpg)
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
![Page 11: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/11.jpg)
mdata(3) = mean(data(cat == 3))mdata(1) = mean(data(cat == 1))mdata(2) = mean(data(cat == 2))
2 Flow control>> for i = 1:3
mdata(i) = mean(data(cat == i))
end
11
i = 2i = 3i = 1
![Page 12: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/12.jpg)
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
do something
else
do something different
end
end
12
![Page 13: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/13.jpg)
2 Flow control
13
![Page 14: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/14.jpg)
2 Flow control The ‘while’ command
>> while statement
commands
end
Waiting Reading
14
>> fid = fopen(‘results.txt'); fline = ‘’; while tline ~= -1 disp(tline) tline = fgetl(fid); end fclose(fid);
>> while mean(results) > 10 ind = results ~= max(results) results = results(ind) end
![Page 15: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/15.jpg)
2 Flow control We can use flow control to display results for each of
several experiments on separate plots.
15
mresult = mean(results)for i = 1:3 figure plot(results(:, i), ‘b.-’) hold on plot([1:10], repmat(mresult(i), 1, 10), ‘r-’) hold offend
![Page 16: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/16.jpg)
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:
16
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 offend
![Page 17: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/17.jpg)
3 Functions
17
![Page 18: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/18.jpg)
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
![Page 19: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/19.jpg)
3 Functions>> sortrows(data, col)
19
![Page 20: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/20.jpg)
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
![Page 21: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/21.jpg)
3 Functions To find out what outputs a function can return use the
help command
21
![Page 22: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/22.jpg)
3 Functions>> [sdata, ind] = sortrows(data, col)
22
![Page 23: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/23.jpg)
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
![Page 24: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/24.jpg)
3 Functions
24
![Page 25: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/25.jpg)
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
![Page 26: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/26.jpg)
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
![Page 27: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/27.jpg)
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
![Page 28: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/28.jpg)
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
![Page 29: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/29.jpg)
4 Cell Arrays
29
![Page 30: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/30.jpg)
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
![Page 31: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/31.jpg)
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
![Page 32: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/32.jpg)
5 Plots
32
![Page 33: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/33.jpg)
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
![Page 34: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/34.jpg)
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-’)
hold off
print(‘-bmp’, [‘c:\users\tom\desktop\’, results(i).label])
end
34
![Page 35: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/35.jpg)
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
![Page 36: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/36.jpg)
5 Plots
>> subplot(2,2,1)
36
43
21
![Page 37: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/37.jpg)
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
![Page 38: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/38.jpg)
5 Plots
38
![Page 39: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/39.jpg)
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
![Page 40: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/40.jpg)
5 Plots Inside/outside Best/Bestoutside
40
Northwest NortheastNorth
South SoutheastSouthwest
EastWest
![Page 41: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/41.jpg)
5 Plots
Colour bars can be repositioned in the same way:
>> h = colorbar
>> set(h, ‘Location’, ‘North’)
41
![Page 42: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/42.jpg)
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
![Page 43: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/43.jpg)
5 Plots
Surface plot
>> surf(matrix)
>> colorbar
>> axis([1 50 1 50 0 1])
>> title('Surface Plot');
>> xlabel('x')
>> ylabel('y')
>> zlabel('z')
43
![Page 44: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/44.jpg)
5 Plots
Contour
>> contour(data)
>> colorbar
>> xlabel('x')
>> ylabel('y')
>> zlabel('z')
>> title('Contour Plot');
>> axis([1 50 1 50])
44
![Page 45: Introduction to MATLAB session 2 Simon O’Keefe Non-Standard Computation Group sok@cs.york.ac.uk.](https://reader033.fdocuments.us/reader033/viewer/2022051401/56649d615503460f94a43baf/html5/thumbnails/45.jpg)
5 Plots All of these can be use in conjunction with subplot,
therefore, you can display several different plot types in one figure
45