MATLAB Part 2 - Matlab as a graphing calculator

Dave White

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)

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,[],':')

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

%switches are

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

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';

Pre-allocation

THINK IF YOU CAN DO YOUR OPERATION WITHOUT A LOOP FIRST

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

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

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

octave

Writing Functions

Difference between a function and a script

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

Also comment the body of your function for later reference

ADD IN COMMENTS

TEST HELP

BootStrap Example - part 1

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

Bootstrap Theory

Resampling

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]=data_gen();
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

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