%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
MATLAB QUICK REFERENCE AND FUNCTION/CLASS TEMPLATES %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
INDEXING & MATRIX REFERENCING %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
NOTE: Matlab uses indexing that starts at 1, not 0
a'; %
Transpose vector/matrix 'a'
a(1); % Return
first element of vector 'a'
a(1,:); % Return
first row of matrix 'a' (all columns)
a(:,1); % Return
first column of matrix 'a' (all rows)
a(i:j:end);
% Extract every jth value starting at i until the last value
%
Note: 'end' keyword can be used to refer to last index without using size()
method
a(1:5,
10:20) %
Return matrix rows 1 through 5 and columns 10 through 20 of 'a'
[r,c]=size(a); % Find
number of rows & columns in matrix 'a'
length(a); % Length
of vector 'a'
size(a,d); % Find
length of 'd'th dimension, e.g. 1=rows,2=columns,3=z
find(a
> 1); % Returns list of indexes in 'a' whose value is >1. Can
use any logical e.g. a=1
[r,c]=find(a); %
Returns list of all indexes with nonzero values, in this case row/col index
pairs from a 2-D matrix
zeros(r,c);
% Creates a r-rows by c-columns matrix of zeros
ones(r,c); %
Creates a r-rows by c-columns matrix of ones
rand(r,c); %
Creates a r-rows by c-columns matrix of pseudo-random numbers from the 0-1
scale (uniform dist)
%%%%%%%%%
%
Spans %
%%%%%%%%%
linspace(a,b,n); %
Creates a row vector that spans 'a' to 'b' in 'n' number of linearly spaced
segments
logspace(a,b,n); %
Creates a row vector that spans 10^a to 10^b in 'n' points
x=a:n:b; %
Creates a row vector from 'a' to 'b' spaced by value 'n'
repmat(A,r,c); % Tile
matrix A 'r' times in the rows direction, 'c' times in the cols direction
flip(A,<dim>); % Flip
order of a vector/matrix, optionally along a specified dimension
horzcat(A,B); %
Horizontally concatenate vectors/matricies A, B, C, D, etc.
vertcat(A,B); %
Vertically concatenante vectors/matricies A,B,C,D, etc.
%%%%%%%%%%%
%
FIGURES %
%%%%%%%%%%%
close all;
% Close all open figures
figure; % Create
new figure
figure(1); % Select
given figure and make it active, or create one with given handle
subplot(numRows,numCols,selectActivePlotNum);
% Create framework for multiple plots within one figure
and/or select one
plot(x,y,<LineSpec>); % X
values, corresponding Y values, LineSpec optional
%
LineSpec is a string composed of concatenating the following specifiers e.g.
'--xc'
%
Note: LineSpec with Marker but no Style will plot only markers without a line
%
Styles: '-'Solid | '--'Dashed | ':'Dotted | '-.'Dash-Dot
%
Markers: 'o' '+' '*' '.' 'x' 's'square
'd'diamond '^'triangle 'v'triangle & others...
%
Colors: 'y'yellow | 'm'magenta | 'c'cyan | 'r'red | 'g'green | 'b'blue |
'w'white | 'k'black
stem(x,y); % Plot
discrete sequence data
hist(data,<nbins>);
% Plot histogram of 10 equally spaced bins, or bins as
specified
histfit(data,<nbins>,<distToFit>); % Plot
histogram with best-fit distribution
normplot(data);
% Normal probability plot i.e. normal quantile plot
gcf; % 'Get
Current Figure' Returns handle/reference to active figure
gca; % 'Get
Current Axis' Returns handle/reference to active axis
%
Note: for one-time plots it can be easier to format using Show Plot Tools in
menubar
%
Note: TeX markup can be used in strings
%
Note: Formatting/plot commands are applied to the currently active figure
title({'Main Title Here';'\fontsize{8}Smaller
Subtitle Here'});
xlabel('X Axis Units');
ylabel('Y Axis Units');
xlim([xmin
xmax]); %
Manually set X limits for plot
ylim([ymin
ymax]); %
Manually set Y limits for plot
saveas(gcf,'figure.png'); % Save
figure as image
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
Loops and Logical Control %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:n:10 % for(i=1;i<=10;i+=n)
% Do
Things
end
if <logical statement>
% Do
Things
elseif <logical statement>
% Do
Things
else
% Do
Things
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Curve
Fitting & Regression %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fitobject
= fit(x,y,fitType); % REFER TO MATLAB HELP/DOCUMENTATION for details - Curve
Fitting Toolbox
plot(fitobject,x,y,{'fit','residuals','deriv1'}); % Plot fit along with input data, as well as residuals vs.
fit and 1st derivative
%%%%%%%%%%%%%
%
FUNCTIONS %
%%%%%%%%%%%%%
%
Note: Main function names and corresponding filenames should match.
%
Note: Any additional functions in an m-file beyond the first/main function
%
are 'local functions' with calling scope limited to the main function
function [returnA, returnB] = functionName(inputA, inputB, varargin)
%functionName(inputA,
inputB, <variable number of arguments>)
% Detailed explanation here
n=nargin; % Number
of input arguments
end
%%%%%%%%%%%
%
CLASSES %
%%%%%%%%%%%
classdef exampleClass < handle
% Inheriting from handle is
necessary to be able to refer to class instance
%EXAMPLECLASS
Summary of this class goes here
% Detailed explanation goes here
properties
Data;
end
methods
function obj=exampleClass(input) % Constructor
obj.Data=input;
end
function []=methodOne(obj,inputArg)
% This
function would be called by exampleClass.methodOne(inputArg)
% The
first argument is a reference/handle to the class instance
% This
function does not return a value
obj.Data=inputArg; % This
type of statement will change the class instance's variable value
end
end
end
%%%%%%%%%
%
OTHER %
%%%%%%%%%
%
NOTE: any statement without a trailing semi-colon will display the result in
the command window
%
General suggestions
%
• Use the workspace variable explorer when creating complex matrixes to
visually validate your code is creating what you expect regarding dimensions
etc.
%
• Make liberal use of the debugger and the capability to perform commands in
the Command Window and see workspace variables DURING debugging to explore what
your code is doing
% Keyboard Shortcuts:
% • Ctrl-R comments line(s)
% • Ctrl-T un-comments
line(s)
% • Tab to indent line(s)
(select multiple if desired)
% • Shift-Tab to de-indent
line(s) (select multiple if desired)
clear; %
Delete/destroy workspace variables
clc; % Clear
command window
isempty(A);
% Check whether variable A is an empty array
fprintf('String %.1d \n',value); % Print
strings and values to cons