Table of Contents

1 Part 2

1.1 Editor

more than just a couple of semicolons, use the editor
indentation is good form, but not required
tabs or spaces?…
Run
Comments - %
continue on next line …
Sections - %%
Run section
be nice to your future self and others - comment and format your code to look nice

1.2 Writing Scripts

Runs just like inputting a bunch of commands in the commandline
all variables will end up in your workspace
Writing a script is the best way to begin writing a function

1.3 Writing Functions

a command with an input and output
functions for just about every essential mathematical operation
difference between a function and a script
different workspaces
writing a function, start out in a script then make it a function

name of function needs to be the same as the filename
comment section
function syntax
multiple functions

if you have multiple functions of the same name, matlab will choose for you without warning
show example test1.m directory/test1.m
which function

SHOW EXAMPLE FUNCTIONS
daVinciPatchFname.m
divisor.m
fouriercon.m
plotting at the end
loadLRSIimage.m
good comment section
good input handling

multiple functions

1.3.1 EXERCISE, Solve quadratic equation

function [ansP, ansN] = quadratic(a,b,c)
% solve for both solutions of quadratic equation
ansP = -b + sqrt(b2-4*a*c)/(2*a)
ansN = -b - sqrt(b2-4*a*c)/(2*a)

OR

function [Ans] = quadratic(a,b,c)
% solve for both solutions of quadratic equation
Ans=zeros(2,1)
Ans(1) = -b + sqrt(b2-4*a*c)/(2*a)
Ans(2) = -b - sqrt(b2-4*a*c)/(2*a)

1.4 Conditional statements

can also do in multiple lines
a=3;
b=3;
if a==b; disp('These are the same'); elseif a==(b*-1); disp('These have the same magnitude'); else; disp('these are not the same'); end
hard to read. can do this in mulitple lines

if a==b %no semicolon requred
disp('These are the same')
elseif a==(b*-1) %no semicolon requred
disp('These have the same magnitude');
else %no semicolon requred
disp('these are not the same');
end

1.5 Switch case

var=randi(10,1)
switch var
case 1
text=('one')
case {2,3}
text=('2 or 3')
case {4}
text=('4')
case 5
text=('5')
otherwise
text=('greater than 5')
end

name='Dave';
switch name
case 'Dave'
num=1
case 'Michael'
num=2
otherwise
num=3
end

return to while example

1.6 For Loops

assigning a temporary variable from a row vector on each iteration
3 statement minimum
for i = 1:9; b=b+1; end;

can also do in multiple lines
b=0;
for i = 1:9 % no semicolon required
i
b=b+2
end

A=ones(10,1)
range=1:9
B=zeros(length(A),length(range));
for i = range
B(:,i)=A*i;
end

s = 10;
H = zeros(s);
for c = 1:s
for r = 1:s
H(r,c) = 1/(r+c-1);
end
end

preallocating - why?
more likely to spit out an error if something goes wrong (wrong sizes)
memory is preallocated, so you don't have to wait for the loop to return an error

A=rand(10);
B=zeros(size(A,1),size(A,2),2)
for i = 1:size(A,1)
B(i,:,1)=A(i,:)
B(i,:,2)=A(i,:)+3./2
end

1.7 While loops

i=1
while true
i=i+1
end

run until some condition is no longer met
a=10
b=1
while a>b
b=b+1
end

run until some condition is met
a=10
b=1
while true
b=b+1
if a==b
break
end
end

OR

a=10
b=1
while true
b=b+1
if a~=b
continue
end
break
end

break
continue
also work in for loops

while true
response=input('What is your age? ','s')
age=num2str(response)
if age < 0
disp('I do not believe that you are from the future.')
continue
end
break
end

1.8 Debugging Basics

When traceback is not clear
Commenting out code
printing and non semi-colon
More advanced in next lecture
Most common errors
closing a bracket or parenthesis
indexing/subscripting -> trying to fit wrong dimension

1.9 Error handling

try; catch ME; rethrow(ME); end

A=[1 3 4];
B=[1 3 4];

A=[1 3 4];
B=[1 3 4 4];

try
A*B
break
catch ME
if (strcmp(ME.identifier,'MATLAB:innerdim'))
B=B';
A*B
else
rethrow(ME)
end
end

try
end

ME.message
struct -> variable with properties
isfield(ME,'message')
properties can have proprties
properties can be any datatype
warning
error
assert -> throw error if condition is not met

1.10 dbstop etc

profile
dbstop in function
dbstop in function at line
dbstop if error
dbcont
dbstep
dbstack
dbstatus
dbclear
error
warning
movies
for
draw now
pause(.1)
end

keys.space=32; %Space
keys.L=28; %LEFT
keys.R=29; %RIGHT
keys.U=30; %UP
keys.D=31; %DOWN
keys.r=114; %DOWN
keys.esc=27;
keys.zero=48;
for
draw now
k = double(get(gcf,'CurrentCharacter')); % NOTE uncomment to see keycodes on keypress
end

1.11 Statistics

smp=rand(10000,1);
histogram(smp,20)

smp=normrnd(2,3,[10000,1]);
histogram(smp);
mvnrand

m=linspace(-5,10,50);
Mu=2
Sigma=1.5
p=normpdf(m,Mu,Sigma)
plot(p)

P=normcdf(m,Mu,Sigma)
plot(P)

%putting it all together
function [p]=mvn()

m=linspace(-5,5,50);
Mu=[0 0]
if ~exist('Sigma','var')
Sigma=[1 0; …
0 1];
end
nM=length(m);
[M1,M2]=meshgrid(m);
p=mvnpdf([M1(:) M2(:)],Mu,Sigma);
p=reshape(p,nM,nM);

figure(938)
subplot(1,2,1)
imagesc(p)
axis square

subplot(1,2,2)
surf(p)
axis square
colormap summer

fmincon - one of the hardest matlab function to use

1.12 Input output handling

defaults
isempty
exist
scope
assignin -> send variable from one workspace to another
assignin('base','Abase',Afcn)
evalin -> run an experession in another workspace
within function
evalin('base','A=num2str(A)')
Global - don't use just because it is easy
static
varargin varargout
structs
input parsing

functionA('variableA',varWhatever)

functionA(varargin)
p = inputParser('variableA',variableA);
p.addParameter('variableA','',@ischar);
variableA =p.Results.variableA;

1.13 Parallelization

servers/clusters
bash (shell)
nodesktop mode
need a different editor
nano
*vim - universal (steep learning curve)
*emacs - keybindings in terminal (steep learning curve)
directory commands
ls
pwd
move
mkdir
system calls
parfor variables
rules:
Only 1 parfor at a time
parfor; parfor; end; end
independent (variables must not depend on previous interation)
parfor t=1:10; x=(t-1); end
increasing, positive, integer
no breaks

1.14 Path

path
addpath
genpath
path

1.15 misc

rand(10)
rng('shuffle')
rand(10)

rng(2)
rand(10)
rng(2)
rand(10)

short-circuits && and ||

changes properties of figure objects
f=figure(1)
gca - axes
gcf - figure
set
get

get(gcf,'CurrentCharacter')

1.16 Intro to object oriented programming

classes - custom data structures
objects - variables created from a class
properties - variables nested within a class
modules - subroutines of a class
Matlab has objects, but is not object oriented
example:
varA="this is a string"
python:
out=varA.split()
out=["this", "is", "a, "string"]
matlab;
out=strsplit(varA)
out=["this", "is", "a, "string"]
Matlab is function oriented with heavy struct usage

classdef
properties
var1
var2
end
methods
function
end
function
end
end

1.17 in class projects

a function that returns all divisors of a given number
plot 1/x, but at x=zero plot a point at zero (hint: need to use plot & scatter)

1.18 Conclusion

Everything else is just functions
fmincon - optimization - most advanced

Author: Dave White

Created: 2018-10-06 Sat 13:44

Validate