MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
1%% Code sections start with two percent signs. Section titles go on the same line.
2% Comments start with a percent sign.
3
4%{
5Multi line comments look
6something
7like
8this
9%}
10
11% Two percent signs denote the start of a new code section
12% Individual code sections can be run by moving the cursor to the section followed by
13% either clicking the "Run Section" button
14% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (macOS)
15
16%% This is the start of a code section
17% One way of using sections is to separate expensive but unchanging start-up code like loading data
18load myFile.mat y
19
20%% This is another code section
21% This section can be edited and run repeatedly on its own, and is helpful for exploratory programming and demos
22A = A * 2;
23plot(A);
24
25%% Code sections are also known as code cells or cell mode (not to be confused with cell arrays)
26
27
28% commands can span multiple lines, using '...':
29 a = 1 + 2 + ...
30 + 4
31
32% commands can be passed to the operating system
33!ping google.com
34
35who % Displays all variables in memory
36whos % Displays all variables in memory, with their types
37clear % Erases all your variables from memory
38clear('A') % Erases a particular variable
39openvar('A') % Open variable in variable editor
40
41clc % Erases the writing on your Command Window
42diary % Toggle writing Command Window text to file
43ctrl-c % Abort current computation
44
45edit('myfunction.m') % Open function/script in editor
46type('myfunction.m') % Print the source of function/script to Command Window
47
48profile on % turns on the code profiler
49profile off % turns off the code profiler
50profile viewer % Open profiler
51
52help command % Displays documentation for command in Command Window
53doc command % Displays documentation for command in Help Window
54lookfor command % Searches for command in the first commented line of all functions
55lookfor command -all % searches for command in all functions
56
57
58% Output formatting
59format short % 4 decimals in a floating number
60format long % 15 decimals
61format bank % only two digits after decimal point - for financial calculations
62fprintf('text') % print "text" to the screen
63disp('text') % print "text" to the screen
64
65% Variables & Expressions
66myVariable = 4 % Notice Workspace pane shows newly created variable
67myVariable = 4; % Semi colon suppresses output to the Command Window
684 + 6 % ans = 10
698 * myVariable % ans = 32
702 ^ 3 % ans = 8
71a = 2; b = 3;
72c = exp(a)*sin(pi/2) % c = 7.3891
73
74% Calling functions can be done in either of two ways:
75% Standard function syntax:
76load('myFile.mat', 'y') % arguments within parentheses, separated by commas
77% Command syntax:
78load myFile.mat y % no parentheses, and spaces instead of commas
79% Note the lack of quote marks in command form: inputs are always passed as
80% literal text - cannot pass variable values. Also, can't receive output:
81[V,D] = eig(A); % this has no equivalent in command form
82[~,D] = eig(A); % if you only want D and not V
83
84
85
86% Logicals
871 > 5 % ans = 0
8810 >= 10 % ans = 1
893 ~= 4 % Not equal to -> ans = 1
903 == 3 % equal to -> ans = 1
913 > 1 && 4 > 1 % AND -> ans = 1
923 > 1 || 4 > 1 % OR -> ans = 1
93~1 % NOT -> ans = 0
94
95% Logicals can be applied to matrices:
96A > 5
97% for each element, if condition is true, that element is 1 in returned matrix
98A( A > 5 )
99% returns a vector containing the elements in A for which condition is true
100
101% Strings
102a = 'MyString'
103length(a) % ans = 8
104a(2) % ans = y
105[a,a] % ans = MyStringMyString
106
107
108% Cells
109a = {'one', 'two', 'three'}
110a(1) % ans = 'one' - returns a cell
111char(a(1)) % ans = one - returns a string
112
113% Structures
114A.b = {'one','two'};
115A.c = [1 2];
116A.d.e = false;
117
118% Vectors
119x = [4 32 53 7 1]
120x(2) % ans = 32, indices in MATLAB start 1, not 0
121x(2:3) % ans = 32 53
122x(2:end) % ans = 32 53 7 1
123
124x = [4; 32; 53; 7; 1] % Column vector
125
126x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
127x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9
128
129% Matrices
130A = [1 2 3; 4 5 6; 7 8 9]
131% Rows are separated by a semicolon; elements are separated with space or comma
132% A =
133
134% 1 2 3
135% 4 5 6
136% 7 8 9
137
138A(2,3) % ans = 6, A(row, column)
139A(6) % ans = 8
140% (implicitly concatenates columns into vector, then indexes into that)
141
142
143A(2,3) = 42 % Update row 2 col 3 with 42
144% A =
145
146% 1 2 3
147% 4 5 42
148% 7 8 9
149
150A(2:3,2:3) % Creates a new matrix from the old one
151%ans =
152
153% 5 42
154% 8 9
155
156A(:,1) % All rows in column 1
157%ans =
158
159% 1
160% 4
161% 7
162
163A(1,:) % All columns in row 1
164%ans =
165
166% 1 2 3
167
168[A ; A] % Concatenation of matrices (vertically)
169%ans =
170
171% 1 2 3
172% 4 5 42
173% 7 8 9
174% 1 2 3
175% 4 5 42
176% 7 8 9
177
178% this is the same as
179vertcat(A,A);
180
181
182[A , A] % Concatenation of matrices (horizontally)
183
184%ans =
185
186% 1 2 3 1 2 3
187% 4 5 42 4 5 42
188% 7 8 9 7 8 9
189
190% this is the same as
191horzcat(A,A);
192
193
194A(:, [3 1 2]) % Rearrange the columns of original matrix
195%ans =
196
197% 3 1 2
198% 42 4 5
199% 9 7 8
200
201size(A) % ans = 3 3
202
203A(1, :) =[] % Delete the first row of the matrix
204A(:, 1) =[] % Delete the first column of the matrix
205
206transpose(A) % Transpose the matrix, which is the same as:
207A.' % Concise version of transpose (without taking complex conjugate)
208ctranspose(A) % Hermitian transpose the matrix, which is the same as:
209A' % Concise version of complex transpose
210 % (the transpose, followed by taking complex conjugate of each element)
211
212
213
214
215
216% Element by Element Arithmetic vs. Matrix Arithmetic
217% On their own, the arithmetic operators act on whole matrices. When preceded
218% by a period, they act on each element instead. For example:
219A * B % Matrix multiplication
220A .* B % Multiply each element in A by its corresponding element in B
221
222% There are several pairs of functions, where one acts on each element, and
223% the other (whose name ends in m) acts on the whole matrix.
224exp(A) % exponentiate each element
225expm(A) % calculate the matrix exponential
226sqrt(A) % take the square root of each element
227sqrtm(A) % find the matrix whose square is A
228
229
230% Plotting
231x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1
232y = sin(x);
233plot(x,y)
234xlabel('x axis')
235ylabel('y axis')
236title('Plot of y = sin(x)')
237axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1
238
239plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot
240legend('Line 1 label', 'Line 2 label') % Label curves with a legend
241
242% Alternative method to plot multiple functions in one plot.
243% while 'hold' is on, commands add to existing graph rather than replacing it
244plot(x, y)
245hold on
246plot(x, z)
247hold off
248
249loglog(x, y) % A log-log plot
250semilogx(x, y) % A plot with logarithmic x-axis
251semilogy(x, y) % A plot with logarithmic y-axis
252
253fplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5
254
255grid on % Show grid; turn off with 'grid off'
256axis square % Makes the current axes region square
257axis equal % Set aspect ratio so data units are the same in every direction
258
259scatter(x, y); % Scatter-plot
260hist(x); % Histogram
261stem(x); % Plot values as stems, useful for displaying discrete data
262bar(x); % Plot bar graph
263
264z = sin(x);
265plot3(x,y,z); % 3D line plot
266
267pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value
268contour(A) % Contour plot of matrix
269mesh(A) % Plot as a mesh surface
270
271h = figure % Create new figure object, with handle h
272figure(h) % Makes the figure corresponding to handle h the current figure
273close(h) % close figure with handle h
274close all % close all open figure windows
275close % close current figure window
276
277shg % bring an existing graphics window forward, or create new one if needed
278clf clear % clear current figure window, and reset most figure properties
279
280% Properties can be set and changed through a figure handle.
281% You can save a handle to a figure when you create it.
282% The function get returns a handle to the current figure
283h = plot(x, y); % you can save a handle to a figure when you create it
284set(h, 'Color', 'r')
285% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
286set(h, 'LineStyle', '--')
287 % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line
288get(h, 'LineStyle')
289
290
291% The function gca returns a handle to the axes for the current figure
292set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis
293
294% To create a figure that contains several axes in tiled positions, use subplot
295subplot(2,3,1); % select the first position in a 2-by-3 grid of subplots
296plot(x1); title('First Plot') % plot something in this position
297subplot(2,3,2); % select second position in the grid
298plot(x2); title('Second Plot') % plot something there
299
300
301% To use functions or scripts, they must be on your path or current directory
302path % display current path
303addpath /path/to/dir % add to path
304rmpath /path/to/dir % remove from path
305cd /path/to/move/into % change directory
306
307
308% Variables can be saved to .mat files
309save('myFileName.mat') % Save the variables in your Workspace
310load('myFileName.mat') % Load saved variables into Workspace
311
312% M-file Scripts
313% A script file is an external file that contains a sequence of statements.
314% They let you avoid repeatedly typing the same code in the Command Window
315% Have .m extensions
316
317% M-file Functions
318% Like scripts, and have the same .m extension
319% But can accept input arguments and return an output
320% Also, they have their own workspace (ie. different variable scope).
321% Function name should match file name (so save this example as double_input.m).
322% 'help double_input.m' returns the comments under line beginning function
323function output = double_input(x)
324 %double_input(x) returns twice the value of x
325 output = 2*x;
326end
327double_input(6) % ans = 12
328
329
330% You can also have subfunctions and nested functions.
331% Subfunctions are in the same file as the primary function, and can only be
332% called by functions in the file. Nested functions are defined within another
333% functions, and have access to both its workspace and their own workspace.
334
335% If you want to create a function without creating a new file you can use an
336% anonymous function. Useful when quickly defining a function to pass to
337% another function (eg. plot with fplot, evaluate an indefinite integral
338% with quad, find roots with fzero, or find minimum with fminsearch).
339% Example that returns the square of its input, assigned to the handle sqr:
340sqr = @(x) x.^2;
341sqr(10) % ans = 100
342doc function_handle % find out more
343
344% User input
345a = input('Enter the value: ')
346
347% Stops execution of file and gives control to the keyboard: user can examine
348% or change variables. Type 'return' to continue execution, or 'dbquit' to exit
349keyboard
350
351% Reading in data (also xlsread/importdata/imread for excel/CSV/image files)
352fopen(filename)
353
354% Output
355disp(a) % Print out the value of variable a
356disp('Hello World') % Print out a string
357fprintf % Print to Command Window with more control
358
359% Conditional statements (the parentheses are optional, but good style)
360if (a > 23)
361 disp('Greater than 23')
362elseif (a == 23)
363 disp('a is 23')
364else
365 disp('neither condition met')
366end
367
368% Looping
369% NB. looping over elements of a vector/matrix is slow!
370% Where possible, use functions that act on whole vector/matrix at once
371for k = 1:5
372 disp(k)
373end
374
375k = 0;
376while (k < 5)
377 k = k + 1;
378end
379
380% Timing code execution: 'toc' prints the time since 'tic' was called
381tic
382A = rand(1000);
383A*A*A*A*A*A*A;
384toc
385
386% Connecting to a MySQL Database
387dbname = 'database_name';
388username = 'root';
389password = 'root';
390driver = 'com.mysql.jdbc.Driver';
391dburl = ['jdbc:mysql://localhost:8889/' dbname];
392javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/
393conn = database(dbname, username, password, driver, dburl);
394sql = ['SELECT * from table_name where id = 22'] % Example sql statement
395a = fetch(conn, sql) %a will contain your data
396
397
398% Common math functions
399sin(x)
400cos(x)
401tan(x)
402asin(x)
403acos(x)
404atan(x)
405exp(x)
406sqrt(x)
407log(x)
408log10(x)
409abs(x) %If x is complex, returns magnitude
410min(x)
411max(x)
412ceil(x)
413floor(x)
414round(x)
415rem(x)
416rand % Uniformly distributed pseudorandom numbers
417randi % Uniformly distributed pseudorandom integers
418randn % Normally distributed pseudorandom numbers
419
420%Complex math operations
421abs(x) % Magnitude of complex variable x
422phase(x) % Phase (or angle) of complex variable x
423real(x) % Returns the real part of x (i.e returns a if x = a +jb)
424imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb)
425conj(x) % Returns the complex conjugate
426
427
428% Common constants
429pi
430NaN
431inf
432
433% Solving matrix equations (if no solution, returns a least squares solution)
434% The \ and / operators are equivalent to the functions mldivide and mrdivide
435x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b.
436x=b/A % Solves xA=b
437
438inv(A) % calculate the inverse matrix
439pinv(A) % calculate the pseudo-inverse
440
441% Common matrix functions
442zeros(m,n) % m x n matrix of 0's
443ones(m,n) % m x n matrix of 1's
444diag(A) % Extracts the diagonal elements of a matrix A
445diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere
446eye(m,n) % Identity matrix
447linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2
448inv(A) % Inverse of matrix A
449det(A) % Determinant of A
450eig(A) % Eigenvalues and eigenvectors of A
451trace(A) % Trace of matrix - equivalent to sum(diag(A))
452isempty(A) % Tests if array is empty
453all(A) % Tests if all elements are nonzero or true
454any(A) % Tests if any elements are nonzero or true
455isequal(A, B) % Tests equality of two arrays
456numel(A) % Number of elements in matrix
457triu(x) % Returns the upper triangular part of x
458tril(x) % Returns the lower triangular part of x
459cross(A,B) % Returns the cross product of the vectors A and B
460dot(A,B) % Returns scalar product of two vectors (must have the same length)
461transpose(A) % Returns the transpose of A
462fliplr(A) % Flip matrix left to right
463flipud(A) % Flip matrix up to down
464
465% Matrix Factorisations
466[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix
467[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues
468[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order
469
470% Common vector functions
471max % largest component
472min % smallest component
473length % length of a vector
474sort % sort in ascending order
475sum % sum of elements
476prod % product of elements
477mode % modal value
478median % median value
479mean % mean value
480std % standard deviation
481perms(x) % list all permutations of elements of x
482find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators,
483 % i.e. find( x == 3 ) returns indexes of elements that are equal to 3
484 % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3
485
486
487% Classes
488% MATLAB can support object-oriented programming.
489% Classes must be put in a file of the class name with a .m extension.
490% To begin, we create a simple class to store GPS waypoints.
491% Begin WaypointClass.m
492classdef WaypointClass % The class name.
493 properties % The properties of the class behave like Structures
494 latitude
495 longitude
496 end
497 methods
498 % This method that has the same name of the class is the constructor.
499 function obj = WaypointClass(lat, lon)
500 obj.latitude = lat;
501 obj.longitude = lon;
502 end
503
504 % Other functions that use the Waypoint object
505 function r = multiplyLatBy(obj, n)
506 r = n*[obj.latitude];
507 end
508
509 % If we want to add two Waypoint objects together without calling
510 % a special function we can overload MATLAB's arithmetic like so:
511 function r = plus(o1,o2)
512 r = WaypointClass([o1.latitude] +[o2.latitude], ...
513 [o1.longitude]+[o2.longitude]);
514 end
515 end
516end
517% End WaypointClass.m
518
519% We can create an object of the class using the constructor
520a = WaypointClass(45.0, 45.0)
521
522% Class properties behave exactly like MATLAB Structures.
523a.latitude = 70.0
524a.longitude = 25.0
525
526% Methods can be called in the same way as functions
527ans = multiplyLatBy(a,3)
528
529% The method can also be called using dot notation. In this case, the object
530% does not need to be passed to the method.
531ans = a.multiplyLatBy(1/3)
532
533% MATLAB functions can be overloaded to handle objects.
534% In the method above, we have overloaded how MATLAB handles
535% the addition of two Waypoint objects.
536b = WaypointClass(15.0, 32.0)
537c = a + b