# matlab cheat sheet

–to insert a column into a matrix…. create a new matrix with the new column and the existing matrix.
–format long g % to display more digits without “e”

%{
multi-line comment
%}

nan(N) % better error detection than
ones(N)
zeros(N)
–Calling another .m script (not a function) — http://stackoverflow.com/questions/5226840/call-a-matlab-script-in-a-script

— print variable with tag
disp([‘x is equal to ‘,num2str(x),’.’])
fprintf(‘TS: row # %in’, foundInHeet);

–“die”

error(‘Every time stamp must match between EWJ/JPP time series’)

— execute a multi-line selection of code
select -> right-click -> evaluate selection
–locate nan’s in a large vector
find(isnan(yourarray))
–code folding
preferences -> editor/debugger

# matlab | index of first +ve value

See the stoch HW8 on Poisson process, where our array has timestamps of each consecutive jump, and we need to find how many jumps by time=2 minutes.

# matlab | string vs cell of 1 string

Many matlab functions work with a string OR a cell of 1 string. So sometimes we don't realize their difference.

You can check the exact type of given stringy thingy with the function class().

To convert a cell into a string, use theVariable{:}

eg: regexp() –> cell

# matlab | find()

I feel a lot of textbooks skip this instrumental function, and other tutorials on this function are not focused. Let’s keep things very simple and focus on the bare essentials.

Focus on a vector, not a matrix.

Focus on find(some logical expression) rather than find(someVector)

Logical indexing is closely related to the find function. The expression A(A > 5) is equivalent to A(find(A > 5)). Therefore, better learn logical indexing first.

# matlab | logical subscripting – learning notes

http://www.mathworks.com/help/matlab/learn_matlab/indexing.html#f2-15124 clearly defines it — “Suppose X is an ordinary matrix and L is a matrix of the same size that is the result of some logical operation. Then X(L)specifies the elements of X where the elements of L are nonzero.”

Note if L has 5 non-zero elements, then length(X(L)) == 5.

I think L must be an array of booleans, not doubles.

But here’s a real illustration in my code:

step = 1/200;
steps = 2/step;
reruns=500;

% generate increments
%rng(0,’twister’); % if we want repeatable
incr = randn(steps,reruns)*sqrt(step);

std(incr) % should  all be around 0.07
hist(incr(:,1))

% random walker positions
p = cumsum(incr);

% select a subset of Columns, using filter on
% “200th ROW and 400th ROW” so
% row expression = wildcard; column expression = filter on Row.
% If we carelessly swap the expressions, matlab won’t warn us!
qualified = p(:, (p(200,:)>0 & p(400,:)>0));

# matlab | foreach loop on matrix

If your original matrix is a column vector, then you better transpose it before using foreach. For a given matrix, foreach takes one column at a time.

# matlab | assign to cell array

% assigning into 2 consecutive cells, using parentheses not braces

outputCell(tmp_newRow, 3:4) = num2cell(betaTukeyN)

% assign to individual cell, using braces, not parentheses

outputCell{end+1, 3} = betaTukeyN(1)

# matlab | a few useful indexing techniques

extract all the odd elements

extract every 3rd element

Reverse the order of elements

–logical subscript

To replace all NaN elements with zero

# matlab | sscanf performance imt str2double

trFolder = 'datammmSH600519T';

tic

for i=1:length(tr1D.textdata(:,4))

tt=tr1D.textdata(i,4);

dummy = sscanf(tt{:}, '%f');

end

toc

%%%%%%%%%%%

tic

str2double(tr1D.textdata(:,4));

toc

# Matlab | clear all except breakpoint

tmp = dbstatus;

save('tmp.mat','tmp')

clear classes % clears even more than clear all

dbstop(tmp)

% clean up

clear tmp

delete('tmp.mat')

# Matlab | extracting string from in a cell array

A(1,1) is still a cell array — 1×1. It's not a string and many functions won't accept it.

myStr = sprintf('%s',A(1,1));

# matlab [] vs ()

paren and brackets are by far the most versatile constructs in matlab. Each has rich contextual meanings. Here is an incomplete sketch.

–Matlab doc on “special characters” —

Brackets are used to form vectors and matrices.

Parentheses are used to enclose subscripts of vectors

A right angle (square) bracket creates a vector or matrix, whereas curly brackets creates a cell array.

When working with numbers, I'd say that 99% of the time, you will use square brackets. Cell arrays allow you to store different types of data at each location, e.g. a 10×5 matrix at (1,1), a string array at (1,2).

# matlab | assign to multiple variables at once

tmp = num2cell(array_of_values);

[j, g, tmpM, tmpL, s] = tmp{:};

# Matlab | full text search across a folder

Find Text in Multiple File Names or Files

You can find folders and file names that include specified text, or whose contents contain specified text. On the Editor tab, in the File section, click Find Files to open the Find Files dialog box. For details, see Finding Files and Folders.