MATLAB PART 2 - Programming

Table of Contents

Examples from this tutorial

https://gitlab.com/opensourcedave/matlabcourse
Download zip
Unzip (on windows click and drag contents to a new directory)
In matlab cd to unzipped directory
(On windows you can click on an empty space of the address bar to get the address. Highlight it, then copy it. Then in matlab paste it after the cd command)

Intro

More complex mathematical operations, want to keep track of everything
Run as one big function or script

Conditional statements
Loops

Any questions on things I covered?

Editor

More than just a couple of lines, use the editor
You can use any editor you like as well.

Comments start with % - won’t be ran

  • <C-/> - comment a whole line with
  • <C-T> - Uncomment a line with

Sections marked by %%

Essetial editor tab buttons

  • Run (F5)
  • Run section (ctrl enter)
  • Run and advance (ctrl shift enter)

Most everything has a shortcut
Hover over buttons and wait to see shortcuts
OR
preferences->keyboard->shortcuts

Writing Scripts

Basic

Just write your commands in the editor
a=100
b=100
f=@(x) x^2-6
f(a)
b(a)

RUN
Click the run button

Comment stuff

%Initial Values
a=100
b=101
%A Quadratic function
f=@(x) x^2-6

%% evaluating functions
f(a) % run a
f(b) % run b

RUN

Suppress Output

%Initial Values
a=100;
b=101;
%A Quadratic function
f=@(x) x^2-6;

%% evaluating functions
f(a); % run a
f(b); % run b

RUN

Excercise

See if you can implement the quadratic function from before as a script

%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

%Lets write a script that solves a quadratic equation
x(1) = -b + sqrt(b^2-4*a*c)/(2*a);
x(2) = -b - sqrt(b^2-4*a*c)/(2*a);

%save as "quadratic"
%assign some variables
a=1;
b=0:
c=0;
quadratic

a=1
b=-1
c=-2
quadratic

Writing Functions

Difference between a function and a script

  • Other than input and output, functions create variables in different workspaces
  • Good practice for writing a function - start out in a script then make it a function

Lets turn our script into a function

function x = quadratic(a,b,c)

Name of function needs to be the same as the filename*
Comment section - what it does, what inputs and outputs mean
Remember: matlab will not warn you if there are multiple functions of the same name

  • If you have multiple functions of the same name, matlab will choose for you without warning
  • Use ’which’ function

Also comment the body of your function for later reference

ADD IN COMMENTS

TEST HELP

Conditional statements

IF ELSE ELSEIF
Conditional statements allow for certain code to be ran if a certain condition is met.
In a single if-statement, you can have as many conditions as you like. The first must always be ’if’.
’elsif’ and ’else are optional

Basic
imagine name as an input to a function

name='DNW'
if strcmp(name,'DNW'):
  firist='David;
elseif strcmp(name,'JLB'):
  first='Justin'
else
  first='unkown'
end

Example with numbers
imagine a & b as inputs to a function

a=randi(10,1)-5;
b=randi(10,1)-5;
if a==b %if this condition is met
  disp('Values are the same') %run this nested indented code
  c=3;
elseif a==(b*-1) %This condition in only checked if the previous statement was false
  disp('Values have the same magnitude');
elseif a==0      %This condition in only checked if the previous statements were false
  disp('A is zero');
else %no semicolon requred
  disp('Values are not the same');
end

ORDER OF STATEMENTS
Multiple conditions may in fact be true, but the entire block (starting with ’if’ ending with ’end’) will erminate after the indeted code associated with the first match is met.
Therefore, it may be necessary to further condition your code, or use multiple if statements.
Semicolons do nothing on lines containing ’if’, ’elseif’, ’else’, or ’end’

a=5
if a==5
  disp('a is five')
elseif abs(a)==5
  disp('magitude of a is five')
end

SIMPLIFY TO SINGLE 1 OR ZERO
Be careful about dimensions with if statements
Matlab will use the default of all() on your matrix

a=randi(2,10)-1;
a=sum(sum(randi(2,10)-1));
if a
  disp('True')
else
  disp('False')
end


a=randi(2,2)-1;
if all(a)
  disp('All a are 1')
elseif any(a)
  disp('Some a are 0')
end

Conditional statements part 2

Indentation is good form, but not required
If you are running the matlab editor, this is usually done automatically

function [b,ind] = isalpha(in)
%determine whether string is contains only letters
  alphaV=['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'];
  alphaV=alphaV(:);
  if  any(~ismember(in,alphaV));
      b=1;
  else
      b=0;
  end
end %This end is required if multiple functions are in the same file

MULTILPLE FUNCTIONS & SCOPE
If I include multiple functions to a single file, your workspace is only aware of the function with the same name as the filename. However, that function itself is away of the additional functions.

% Put the below function in the same file as 'isalpha'!
% REmove the alphaV lines
function A = alphaV()
  A=['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'];
  A=A(:);
end
%By including a secondary funciton in the same file, we have limited the scope of this additional function.
%That is, it can only be called on by code within the file.

Multiple conditions & short circuiting

COMBINING LOGIC & SHORT CIRCUITING
You can combine logical statements in your if statments using & and |
just like we did with basic logic.
But, you should also use && and || instead

#Defaults
clear
~exist('A','var') || isempty(A) % two symbols is a "short-circuity", no error
~exist('A','var') | isempty(A)  % this line should result in an error

exist('A','var') && ~isempty(A) % this one won't create an error
exist('A','var') & ~isempty(A)  % this one will create an error

if ~exist('A','var') || isempty(A)
    disp('A is not assined to a value. I''m setting it to a default value')
    A=0;
end

%This type of behavior is useful for functions with optional inputs
function my_plot(x,y,color,shape)
  if ~exist('color','var')  || isempty(color)
    color='k';
  end
  if ~exist('shape,'var')  || isempty(shape)
    shape='.';
  end
  plot(x,y,[color shape])
end

my_plot(x,y)
my_plot(x,y,[],':')

For Loops

LOOPS
Loops allow you to repeat code as many times as you want.
For loops let you repeat that code, but each time it repeats, you can have a variable (commonly i) take on a specific number

disp(10)
pause(1)
disp(9)
pause(1)
disp(8)
pause(1)
disp(7)
% ...
disp(10)
pause(1)

%VS

r=1:10
for i = r
    disp(i)
    pause(1)
end

VISUALIZE A HISTOGRAM
Assigning a temporary variable from a row vector on each iteration

Visualizing a sampling procedure as a movie:
A=[]
for i = 1:100  %We are repeating the indented code 100 times. Systematically i will take on values 1:100 with each iteration
    A=[A; randn(10,1)]
    histogram(A)
    drawnow
    pause(.1)
end

ANY ROW VECTOR
You don’t have to have i = 1:100. You can replace 1:100 with any row vector!

for i = randi(10,1,10)
  display(['Draw ' num2str(i) ' cards.'])
  input('Press Return');
end

Pre-allocation

THINK IF YOU CAN DO YOUR OPERATION WITHOUT A LOOP FIRST

  • much faster to run and write

OTHERWISE
Preallocate - assining placeholder values in matrix/cell before its populated with desired values

  • Makes sure that you have enough memory before you run
    (Breaks on first line rather than later)
  • Guarantees the proper dimensions

Preallocation speeds things up

clear
tic
x=0;
for i = 2:100000000
  x(i)=x(i-1)+10;
end
toc

x=zeros(1,100000000);
tic
for i = 2:100000000
  x(i)=x(i-1)+10;
end
toc

Preallocation can avoid waiting to find out if you have enough memory
#+BEGINSRC octave
for i = 1:10000
A(:,:,:,i)=zeros(100,100,100)*i;
end

zeros(100,100,100,10000)
for i = 1:10000
A(:,:,:,i)=zeros(100,100,100)*i;
end
#+ENDSRC octave

BootStrap Example - part 1

Very practical statistics example
Putting lots of concepts together
Example of what you can really do with matlab.

Bootstrap Theory

  • Estimating a population mean from some samples
  • Say height of UPenn body
  • How confident can we be in our estimate?
  • If there is a lot of variation in the data, we need more samples
  • How much is the variation in our sample biasing our estimate?

Resampling

  • If we resampled our data, how different would the mean be?
  • To avoid sampling bias with our resampling, lets resample many times.
  • Look at the distribution of means
  • If variation of our resampled means is large - we can’t be too confident in our estimate.

#+beginsrc octave
function [SEM MM]=SEMboot(data,nBootS,bPlot)
% Bootstrapping to get Standard error of the mean
% be used for confidence intervals for the sample mean
if ~exist(’data’,’var’) || isempty(data)
[data,I]=datagen();
else
I=[]
end

% BOOTSTRAP
M=zeros(length(data),1);
for i=1:nBootS
y=datasample(data,length(data),’Replace’,true);
M(i)=mean(y);
end
SEM=std(M);
MM=mean(M(:));
CI=[MM-(SEM*1.96) MM+(SEM*1.96)]; %95 confidence intervals

if bPlot
Plot(data,M,SEM,CI,MM,I)
end
end
#+endSRC octave

BootStrap Example - part 2

function [data,I]=data_gen()
% Generates example data if you have noen
    I=rand(1)*3+5;
    data=normrnd(I,1,100,1);
end

function []=Plot(data,M,SEM,CI,MM,I)
% HANDLE PLOTTING
    figure(1)
    subplot(1,2,1)
    hold off
    [counts,ctrs]=hist(data);
    bar(ctrs,counts)
    y=max(counts);
    Y=[y y];
    hold on
    plot(CI,Y,'r','LineWidth',5)
    plot(MM,y,'kd')
    title('Data')
    axis square
    hold off

    subplot(1,2,2)
    histogram(M);
    axis square
    name=['Mean: ' num2str(mean(data))  newline ...
                   'SEM:  ' num2str(SEM) ];
    if ~isempty(I)
        name=[name newline 'True = ' num2str(I)];
    end
    title(name);
end

While loops

Until not true

a=0
while a>10
  a=a+1
  disp(a)
end

GO UNTIL BREAK

while true
   r=input('Please input your name: ','s');
   if isalpha(r)
      break
   else
      disp('Invalid name. Try again')
   end
end

OR

while true
   r=input('Please input your name: ','s');
   if ~isalpha(r)
      disp('Invalid name. Try again')
      continue % Ends current iteration and begins just under while loop
   end
   break
end

CONTINUE & BREAK IN FOR LOOPS
If using continue on a for-loop, will start on the next iteration value

for i = 1:5
    if mod(i,2)
       disp([i ' is even'])
       continue
    end
    dis([i ' is odd'])
end

Read Lines example

function tlines = txt2lines(fname)
% Opens a text file, returns each line of the file as an element in a cell
fid=fopen(fname);  %opens file
tline = fgetl(fid);%reads file into variable
tlines = cell(0,1);
while ischar(tline)
    tlines{end+1,1} = tline;
    tline = fgetl(fid);
end
fclose(fid); %closes file

LOAD DATA

fname='addquestions.txt';

Switch case

switch-case is like if-statments but more convenient for simple conditions especially if you have a lot of them.

function [txt] = num2literal(num)
switch abs(num)
  case 1
    txt='one';
  case 2
    txt='two';
  case 3
    txt='three';
  case 4
    txt='four';
  case 5
    txt='five';
  case 6
    txt='six';
  case 7
    txt='seven';
  case 8
    txt='eight';
  case 9
    txt='nine';
  case 0
    txt='zero';
  case{Inf,NaN} %Having a case like this is saying Inf | NaN
    txt='infinity';
  otherwise
    if isalpha(num)
      disp('String contains non-number') %We will change this later
    end
end %Note only one end
if num<0
   txt=['negative-' txt];
end

 are

Conclusion

In this tutorial we have covered about 99% of what is commonly used in matlab
There are many options that we didn’t cover in the functions that we went over, so check the documentation
If you want to maintain what we’ve learned here, you should make your next project in matlab/octave

Author: Dave White

Email: davey@cryptolab.net

Created: 2020-07-25 Sat 14:04