View on GitHub

Settings_Matlab

Settings and notes for Matlab

Common MATLAB Functions

Last Updated 2019-05-13 by Adam Lu


General

% Change working directory
cd('pathToDir')

% Assign to a variable with the equal sign
var = 5

% Suppress output with the semicolon
var = 5;

% Comment block
%{
    This is a comment.
    This is also a comment.
%}

% List all variable names in the workspace
who

% Find a class of a variable
class(var)

% Save a variable to a .mat file
save('file.mat', 'var')

% Save a variable to a Version 7.3 .mat file
save('file.mat', 'var', '-v7.3')

% Save a figure
h = figure(id);
saveas(h, 'myFig.png')

% Load variables from a .mat file
load('file.mat', 'var')

% Load variables from a Version 7.3 .mat file
m = matfile('file.mat');
m.var

% Import data from file
data = importdata(filename)

% Remove a variable var
clear var

% Remove all variables in the workspace
clear all

% Remove all variables including hidden variables in the workspace
clear all force hidden

% Close a specific figure
close(fig)

% Close all figures
close all

% Close all figures including hidden figures
close all force hidden

% Clear the command window
clc

% Clear current figure
clf

% Clear and close everything (available in Marks_Functions)
ccc

% Run a script
myScript;

% Step through a file line-by-line
%{
In the Matlab editor, click the horizontal bar to the right of the line number. When the file begins to run, it should stop on that line. Proceed to the next statement by clicking Step.
%}

% Avoid classified error parfor structure
xs = zeros(100, 10);
parfor idx1 = 1:100
	x = zeros(1, 10);
	for idx2 = 1:10
		x(idx2) = val;
    end
    xs(idx1, :) = x;
end

% Get parts of a filename
[filepath, name, ext] = fileparts(filename)

% Construct file path from parts
fullfile(path, parentFolder, folder_or_file)

% Throw error
error(str)

% Get current working directory
pwd

% Print to console
fprintf(message)

% Create string variable
sprintf(message)

% Print in standard output or in message box (available in Adams_Function)
print_or_show_message(message)

% Test if variable or directory exists
exist(arg, argType)

% Evaluate string as command
eval(str)

% Add functions in folder for use
addpath(folder)

% Get all files in a folder
dir(folder)

% Make folder
mkdir(folder)

% Validate number of output arguments
nargoutchk(minArgs,maxArgs)

Built-in constants in MATLAB

Avoid naming variables with these strings:

% Not a number
NaN

% Infinity and negative infinity
Inf
-Inf

% Numbers
pi == 3.1416
e == exp(1)

% Imaginary number
i == j == sqrt(-1)

Dealing with Functions or Scripts

Assume myFun is a function or script:

% Look up the documentation for a function or script in session
help myFun

% Look up the full documentation for a function or script online
doc myFun

% Open the source file for a function or script
open myFun

% Looking for functions or scripts with keywords in descriptions
lookfor keyword

% Header to create a function
function [returnVal1, returnVal2] = funcName(varargin)

% Create an anonymous function
myFun = @(x, y) x + y
myFun(1, 2) == 3

Dealing with Arrays in General

Assume arr is an array:

% Create a row vector
[1, 5, 3]

% Create a column vector
[1; 5; 3]
transpose([1, 5, 3])

% Create a sequence row vector
0:0.25:1
linspace(0, 1, 5)

% Create a sequence column vector
(0:0.25:1)'
transpose(linspace(0, 1, 5))

% Create a 2-D array
arr = [3 4 5; 6 7 8]
arr = [3, 4, 5; 6, 7, 8]

% Create an array of zeros
zeros(nRows, nCols)

% Create an array of ones
ones(nRows, nCols)

% Extract an element from a 2-D array
arr(2, 1)

% Extract a row from a 2-D array
arr(2, :)

% Extract a column from a 2-D array
arr(:, 1)

% Extract the second to last column from a 2-D array
arr(:, end - 1)

% Extract specific columns from a 2-D array
arr(:, [1, 3])

% Linearize an array
arr(:)

% Logical indexing
arr(arr > 3)

% Delete an index
arr(2) = []

% Transpose an array
arr'
transpose(arr)

% Concatenate arrays horizontally
horzcat(arr1, arr2, arr3)

% Concatenate arrays vertically
vertcat(arr1, arr2, arr3)

% Number of elements in an array
numel(arr)

% Number of dimensions of an array
ndims(arr)

% Dimensions of an array
size(arr)

% Size of single dimension in an array
%   dimension: 1 - row; 2 - column
size(arr, dim); 

% Largest dimension of an array
length(arr)

% Unique elements of an array
unique(arr)

% Test if array has no elements
isempty(arr)

% Test if arrays (matrix-wise) are equal
isequal(arr1, arr2)		% treats NaN values as nonequal
isequaln(arr1, arr2)	% treats NaN values as equal

% Get difference between two arrays
setdiff(arr1, arr2)

% Get union between two arrays
union(arr1, arr2)

% Repeat matrix in a dimension
repmat(mat, rows, cols)

% Find index of element in array
find(arr == element)

% Elements of A in B
ismember(A, B)

% Reverse the order of a vector (whether row or column)
arr2 = flip(arr1)

% Reverse the order of each column of a matrix
arr2 = flip(arr1)
arr2 = flip(arr1, 1)
arr2 = flipud(arr1)

% Reverse the order of each row of a matrix
arr2 = fliplr(arr1)
arr2 = flip(arr1, 2)

% Reshape matrix to specified dimensions
arr2 = reshape(arr1, [dim1Size, dim2Size, ..., dimNSize])

% Test/Check structure of array
isvector(arr)
iscolumn(arr)

Operations for numeric arrays

% Element-wise arithmetics
x + y
x - y
x .* y
x ./ y

% Matrix multiplication 
x * y

% Mathematical functions
abs(x)
sqrt(x)
exp(x)
log(x)
log10(x)
log2(x)
sin(x)
cos(x)
tan(x)
factorial(x)
mod(x)

% Test relationships between each pair of elements
x == y			% equal to
x ~= y			% not equal to
x > y
x >= y
x < y
x <= y

% Test type of variable
isinteger(x)
isfloat(x)
isnumeric(x)
isreal(x)
isfinite(x)
isinf(x)
isnan(x)
iscell(x)
isstruct(x)
isscalar(x)

% Test if element is NaN
inan(x)

% Round all elements of an array
round(arr)
floor(arr)		% always round down
ceil(arr)		% always round up

% Maximum/minimum of an array and the first index that matches the maximum/minimum
[v, i] = max(arr)
[v, i] = min(arr)

% Range of all elements of an array
range(arr)

% Sum of all elements of an array
sum(arr)

% Product of all elements of an array
prod(arr)

% Mean of all elements of an array
mean(arr)

% Mean of all element of an array excluding NaNs
nanmean(arr)

% Standard deviation of all elements of an array
std(arr)		% normalized by N-1
std(arr, 1)		% normalized by N

% Standard deviation of all elements of an array excluding NaN
nanstd(arr)		% normalized by N-1
nanstd(arr, 1)		% normalized by N


% Stats over all elements in specific dimensions
%	dim == 1: over columns (returns a row vector); this is default
%	dim == 2: over rows (returns a column vector)
min(arr, [], dim)
max(arr, [], dim)
range(arr, dim)
sum(arr, dim)
prod(arr, dim)
mean(arr, dim)
std(arr, 0, dim)

% Sign of numeric element
sign(arr)

% Diagonal of array (top-left to bottom-right)
diag(arr)

% Bandpass filter each column (available in Adams_Functions)
freqfilter(arr, fc)

% Median filter of each column (available in Adams_Functions)
medianfilter(arr)

% Moving average filter of each column (available in Adams_Functions)
movingaveragefilter(arr)

% Fourier transform of each column
fft(arr)

% Transfer function coefficient of Butterworth filter
[b, a] = butter(n, Wn, 'low') 		% lowpass
[b, a] = butter(n, Wn, 'high') 		% highpass
[b, a] = butter(n, Wn, 'bandpass')	% bandpass
[b, a] = butter(n, Wn, 'stop')		% bandstop

% Check order of filter
N = filtord(b, a)

% Zero-phase digital filtering
filtfilt(b, a, arr)

% Normal probability density function
normpdf(x)

% Differences between adjacent elements (derivative)
diff(arr)		% 1st
diff(arr, 2)	% 2nd

% Remove one dimensions with length of 1
arr = zeros(1,2,3);
size(arr) == [1 2 3]
size(squeeze(arr)) == [2 3]

% Find local maxima
[pks, locs] = findpeaks(data)

% Bin data
[binSize, binEdges] = histcounts(data, numBins)
[binSize, binEdges] = histcounts(data, binEdges)

Operations for logical arrays

% Operations for scalars
x && y			% AND
x || y 			% OR
xor(x, y)		% XOR

% Element-wise operations
~x				% NOT
x & y			% AND
x | y			% OR

% AND over all elements
all(x)

% OR over all elements
any(x)

Dealing with Cell Arrays

% Create a cell array from variables
cellArray = {var1, var2, var3}
cellArray = cell(var1, var2, var3)

% Get var1 as cell
cellArray(var1)

% Get var1 as element
cellArray{var1}

Dealing with Tables

Assume tble is a table:

% Create a table from vectors (can be cell arrays)
table(vec1, vec2, vec3)

% Read table from file
tble = readtable(file)

% Write table to file
writetable(tble, file)

Dealing with Structure arrays

Assume myS is a structure array with fields a and b:

% Extract a field from each structure of a structure array
extractfield(myS, 'a')

Dealing with Character arrays or Strings

Assume str1, str2, str3 are all strings:

% Concatenate strings
strcat(str1, str2, str3)

% Join strings with a delimiter
strjoin(str1, delimiter)

% Compare strings
strcmp(str1, str2)
strcmpi(str1, str2) % case insensitive

% Match regular expression
startIndex = regexp(str, expression)

% Replace substrings
strrep(str, old, new)

% Find substring in string
strfind(str, sub)

Randomization

% Generate a m x n array of random numbers from the Uniform(0, 1) distribution
rand(m, n)

% Generate a m x n array of random integers between 1 and k
randi(k, m, n)

% Generate a m x n array of random numbers from the Normal(0, 1) distribution
randn(m, n)

Wrapper functions

% Apply the same function to each element of an array
arrayfun(@myFunction, array)

% Apply the same function to each element of a cell array
cellfun(@myFunction, array)

% Apply the same function to each row of a table
rowfun(@myFunction, table)

% Apply the same function to each column of a table
varfun(@myFunction, table)

Plots

Different types of plots
% Generate an RGB color from a string (available in Downloaded_Functions)
rgb('DarkGreen')

% Plot a graph y = f(x)
plot(x, y)

% Plot a scatterplot
scatter(x, y, pointSize, pointColor)

% Plot points
points(vec)

% Plot log-log
loglog(x, y)

% Plot semilog
semilogx(x, y)
semilogy(x, y)

% Plot with error bars
errorbar(x, y, err)		% err is error above and below y

% Plot a line from (x1, y1) to (x2, y2)
line([x1, x2], [y1, y2])

% Plot a bar graph
bar(vec)

% Plot a bar graph with confidence intervals (available in Adams_Functions)
plot_bar(means, low, high)

% Plot a simple histogram
histogram(vec)

% Plot a grouped histogram (available in Adams_Functions)
plot_histogram(array)
Plot Customization
% Add title to current plot
title(str)

% Add x-axis label to current plot
xlabel(str)

% Add y-axis label to current plot
ylabel(str)

% Add legend to current plot
legend(labels)

% Adjust axis scales
axis([xmin, xmax, ymin, ymax])
xlim([xmin, xmax])
ylim([ymin, ymax])

% Graphs overlaid on one figure
hold on % turn on
hold off % turn off

% Separate graphs on one figure
subplot(n, m, k) % n x m size, with k linear indexing

% Add colormap (where cmap is a built-in colormap scheme)
colormap(cmap)

% Add annotations
annotation(lineType, x, y)

Type conversion

% Cast between string and numeric
str2num(str1)
str2double(str1)
num2str(num1)
int2str(num1)

% Date to string
datestr(date)

GUI

% Open dialog box to select a directory
dirPath = uigetdir

% Open dialog box to select a file
[file, path] = uigetfile