MATLAB PART 1 - Matlab as a graphing calculator

Table of Contents

Intro

Matlab Philosophy
Non-technical syntax for scientific computing
Everything is an array

Matlab is great for
Learning how to program
Protytyping
Matrices

Other languages
python (better at everything, harder to learn)
R (better at stats)
Julia (fantastic new language)
Ruby
Octave (matlab, but free as in beer AND freedom)

This Lecture’s Goals
Use matlab graphing calculator - plotting
Matrices - batch processing of data

Terminology

Array
Vector or matrix or tensor, that holds a number or character

Vectors
1xN or Nx1 Array
Mathematically - a collection of variables describing a feature/object

Matrices
NxM
Mathematically - a linear “operator” composed of rotations ans scalings
Practically - can be thought of as a collection of vectors

Tensors
NxMxO Array and Arrays beyond 3 dimensions

Examples

1x5 vector

1 2 3 4 5

5x1 vector

1
2
3
4
5

2x3 matrix

1 3 5
2 4 6

Why Use Arrays?
They are compact, easy to organize.
They can be computationally efficent (especially using linear algebra).
You can avoid most looping procedures.

Intuition
Just think of vectors/matrices as tables.

Operators

Operators

% Anything after a percent sign is a comment - it will not be evaluated
8+5                          % + is an operator
8*5                          % Multiplication
(5+3)/2                      % Order of operations apply!

Variables

a=4
b=3
b^2                          % Exponent
ans + 3                      % 'ans' is an automatically assigned variable

Strings

d='t'                        % Character to variable
c='This is a string'         % String to variable

Logic

b=3
a=-3
b > abs(a)                   % Is b greater than abs(a)?
b < abs(a)                   % Is b less than abs (a)?
b ==== 3                     % Is b equal to 3? Notice to equal signs instead of 1.
b =~== 3                     % Is b not equal to 3?
b <= 4                       % Is b less than or equal to 4?
b >= 4                       % Is b greater than or equal to 4?
true==1                      % True and 1 are are the same
false==0                     % False and zero are the same
~true==false                 % ~ takes the compliment of a test (flips the sign)
c === b==4                   % Assigning result of logical test

Combined logic

~(b <= 4)                    % Is b less _greater_ than or equal to 4?
b==5 | abs(a)==3             % OR
b==5 & abs(a)==3             % AND
(b==3 & abs(a)==3 ) | c      % Grouping

Workspace

Workspace variables

A=3
<click on A in workspace>    %Get more info and edit if not too big
clear                        %Clears your variables

Clutter

somelongtexthere<C-c>        %<c-C> gets you a new command-line
clc                          %Clears display

History
Press Up and Down to browse history.
Use comments to keep notes of what you are doing.

Completion

variableA=1
vari<Tab>                    % Use tab completion to make things faster

Functions

Functions take inputs

sqrt(5)                      % Functions have parentheses
abs(-3)
abs(3-7)                     % Inputs can be simplified before being evaluated in functions

Rounding
Many ways to ’round’ a number

round(7/2)                   % Normal rounding
floor(7/2)                   % Round down
ceil(7/2)                    % Round up
fix(7/2)                     % Round towards zero

Zero Inputs

pi()
pi                           % If function takes zero inputs, parentheses are optional

Multiple inputs

times(3,3)                   % Multiple inputs separated by a comma
mod(10,2)                    % Modulus is the remainder of division
                             % 10 divided by 2 has a remainder of zero

Built your own small function (anonymous functions)

f=@(x) x.^2+3                % With 1 input
f(4)
g=@(x,y) x.^2+y.^2+3         % With 2 inputs
g(4,5)

Integration

integral(f,0,1)              % Integrate using anonymous functions

Getting Help
Can’t remember a function
Tab completion
Google

help <function>
doc <function>

DO EXERCISE 1

Loading and saving

Save/Load/Delete

save('myvariables')          % No error means successfully saved
clear                        % Clears all variables from workspace
load('myvariables')          % Restores workspace that was saved

save('myvariables','a','b')  % Optional inputs save only variables A & B
load('myvariables')
clear
load('myvariables')
delete('myvariables')        % .mat is required

NOTE
’save’ and ’load’ take filenames and variable names as inputs.
If i tried saving without quotations

save(myvariables,a,b)

matlab would try read myvariables, a, and b as variables themselves

Files & Directories

File Manager
.m file extension specify scripts and functions (plaintext format)
.mat specifies data (binary format)
using the browser is limiting - I never use it - become apparent next time

Directories/Folders
Where are we saving to?

pwd         %lists current directory
ls          %lists files in current directory

Things that matlab is aware of

  1. Things in your current directory (pwd)
  2. Variables in your workspace
  3. Command History
  4. Things in your path

Create a directory and move into it
Save functions F and g from before in filename ’myfunctions’
f=@(x) x.2+3 With 1 input
g=@(x,y) x.2+y.2+3 With 2 inputs

Path

Your path consists of

  1. Current directory
  2. Directories that are listed in your path variable

Add directories to your path under HOME-> ENVIRONMENT-> PATH
Anything file/directory in your path can be autocompleted and loaded without an explicit structure

WARNING: If you have multiple files of the same name, matlab will use the first one it finds without any warning

which <filename>    % Lists which one matlab will use

Array Basics

Manual array construction

A=[1 2 3]
A=[7/2 11/3 3/2]                  % A row vector (1x3 matrix)
B=[7/2, 11/3, 3/2]                % Also a row vector
C=[7/2; 11/3; 3/2]                % Column vector (3x1 matrix)
A=[7/2 11/3 3/2; 3 2 1; 3, 2, 1]  % A 3x3 matrix

New column with comma and/or space
Either a comma or space is required, or can have both

Functions and operators are designed to work on matrices

A=[7/2 11/3 3/2]
B=[3 2 1]
A+B
A-B

Matrix operations vs element wise operations

A*B                               % Invalid
A'                                % Transpose
A'*B                              % Inner product, a type of dot product - measures similarity between vectors
A*B'                              % Outer product
A.*B                              % Element wise product
A'/B                              % A matrix multiplied by inverse B
A./B                              % Element wise division
A'^B                              % Repeated auto-inner product
A.^B                              % Element wise exponent

Functions on arrays

round(A)
size(A)
size(8)                           % 8 is a 1x1 array!

Combining arrays

A=[1 2 3];
B=[4 5 6];
[A B]
C=[7; 8; 9];
[A C]                             % This doesn't work
[A C']                            % This does

DO EXCERCISE 2

Ranges

1:9                               % Range
1:2:9                             % Increment by 2
1:2:8                             % Non inclusive
L=linspace(1,9,10)                % 10 values equally spaced between 1 and
load('myfunctions')
x=linspace(-5,5,1000)
y=f(x)
plot(x,y);
xlabel('x values')
ylabel('y values')
title('function f')

Grids
Say we want a 2D version of linspace for 3D functions
We need to evaluate at both x and y

L=linspace(1,9,10)         % 10 values equally spaced between 1 and 9
plot(L,L,'.')              % This won't work
[X,Y]=meshgrid(L);         % This distributes x and y
plot(X,Y,'.k')             % This works.

We will return to this after we look at some 2D plots, but first strings ->

Strings

Everything is a matrix, but matrices have datatypes that their elements inherit
2 categories of datatypes
number
characters

Strings are an array of characters

A='this is a string'
B='this is also a string'
size(A)                           %Strings are arrays of characters!
A==B                              %This doesn't compare strings, only individual chars
strcmp(A,B)                       %This compares strings

This means we can combine them like matrices

var='eight
string=['the variable equals ' var '.']                    %Concatenation
var='8'
string=['the variable equals ' var '.']                    %Concatenation
var=num2str(8)
string=['the variable equals ' var '.']                    %Concatenation
string=['the variable ''var'' equals ' var '.']            %Literal quotations
string=['the variable ''var'' equals:' newline var '.']    %newline is function that returns a new-line char
fname=[filesep 'home' filesep 'dambam' filesep 'test1']    %filesep is similar, but returns os agnostic directory char

DO EXERCISE 3

Plotting

Figure 1 - 2D

f=@(x) 1./x;                           % y values of what is being plotted

Note on Continuity
The function f is continuous with inf inite domain
computers need discrete information

Discrete plotting

x=linspace(1,100,10)                   % x values of what is being plotted
y=f(x)
figure(1)                              % Initiates figure 1
plot(x,y)

Increase Resolution

x=linspace(1,100,1000)                 % x values of what is being plotted
y=f(x);                                % y values of what is being plotted
plot(x,y)

Basic Line Properties

plot(x,y,'+')                          % Plot unconnected plus siges
plot(x,y,':')                          % Plot connected dots
plot(x,y,'.')                          % Plot continuous line
plot(x,y,'k')                          % Plot black continuous line
plot(x,y,'r')                          % Plot red continuous line
plot(x,y,'r.')                         % Plot red points
plot(x,y,[.3 .3 .3]                    % RGB values
help plot                              % All properties

KEY VALUES

plot(x,y,'r.','MarkerSize',10)         % Change size of markers
plot(x,y,'r','LineWidth',10)           % Change size of line
plot(x,y,'ro','MarkerEdgeColor','b')   % Change collor of marker border

Labels

title('1/x')                           % Create title
xlabel('this is x')                    % Label x axis
ylabel('this is y')                    % Label y axis
legend('Responses')                    % Add legend with label 'Responses'

Zoom

xlim([0 40])                           % Set x axis limits
ylim([0 .4])                           % Set y axis limits
ylim('auto')
xlim('auto')

Multiple plots on same graph

g=@(x) 1./(x.^2)
z=g(x)
plot(x,z)                              % Erases what we've done
plot(x,y,'ro','MarkerEdgeColor','b')
hold on                                % "Don't erase"
plot(x,z)
legend('Responses1','Responses2')      % Add legend with 2 labels
hold off

DO EXCERCISE 4

Figure 2 - Subplots

Geneate several functions

figure(2)
x=-2:0.25:2;
y1=exp(x)
y2=log(x)
y3=abs(x)
y4=x.^2

Subplots

subplot(2,3,1)
plot(x,y1)
subplot(2,3,3)
plot(x,y2)
subplot(2,3,2)
plot(x,y4)
subplot(2,3,4)
plot(x,y3)

Spanning larger areas

subplot(2,1,2)
plot(x,y3)

Editing a subplot

subplot(2,3,2)
ylim([-3 1])

DO EXCERCISE 5

Figure 3 - 3D

Plotting a 3D function

h=@(x,y) x.*exp(-x.^2-y.^2)  % Same discretization problm before
x=linspace(-2,2,100);        % x values
y=linspace(-2,2,100);        % y values
z=h(x,y)
imagesc(z)                   % This doesn't look right...
size(z)                      % Actually visualizing accross the diagonal

Create Grid

[X,Y]=meshgrid(x,y);         % This distributes x and y
imagesc(X)
imagesc(Y)

Plot using Grid

figure(3)
z=h(X,Y)
size(z)
imagesc(z)                   % Third dimension is represented by color
colorbar
caxis([-.2, .2])
colormap winter
help graph3d

Surf

close                        % Close current figure
surf(z)                      % Third dimension is represented by color and space
                             % If resolution is too high, you can't see the surface
surf(z,'EdgeColor','none')
surf(z,'EdgeColor','none','FaceAlpha',.8)

Images

load('spine')                 % Loads in a variable X
size(X)                       % X is a matrix...
imagesc(X)                    % But an image!
colormap gray
axis image                    % Fix pixel dimensions

Plot on Images
You can plot on top of a figure
First notice that the y axis is upside down
Lets try and plot in the lower left corner

hold on
plot(300,80,'.r','MarkerSize',50)

Also, notice that our plotting indeces are treated backwards

imagesc(X)
plot(80,300,'.r','MarkerSize',50)
colormap gray

This didn’t affect the color of our plotted points

DO EXCERCISE 8

Indexing

Two ways of references elements in a matrix
Indexing - Single value
Subscripts - Two values

Indexing runs down columns then rows:

1 4 7
2 5 8
3 6 9

Subscripts - specifies rows then columns

1,1 2,1 3,1
1,2 2,2 3,2
1,3 2,3 3,3

Either way RC (rows then columns)

A=[80 106 32; 90 70 4; 3 1 2]
A(1)            % First elements
A(1:3)          % Elements 1 through 3
A(:)            % All elements
A(1:end)        % Elements 1 through the last
A(2:end-1)      % Second element to the second to last element
B=A(:)          % Matrix to column vector

ind=find(A==90)

Subscripts

A=[80 106 32; 90 70 4; 3 1 2]
A(1,3)                        % Element in first row, third column
A(1:3,1:2)                    % Elements in 1-3 rows with 1-2 columns
A(1,:)                        % Everything in the first row
A(2:end-1,:)                  % Everything but the first row

Trick to remember:
Index - Individual
Subscripts - Begins with s - plural

[n,m]=find(A==3)
ind=sub2ind(sz,sub1,sub2)
ind=ind2sub(sz,ind)

Editing matrices

Editing Matrices

A=zeros(10)
A(1)=1
A(2:end-1)=0
A(:,1)=rand(10,1);

Deleting values
size(A)

A(1,:)=[]
size(A)
A(1)=[]
size(A)

Combining matrices

B=ones(10)
[A B]
a=1
b=[2 1]
[a b [1 3 4]]
[a b'] invalid

DO EXCERCISE 7

Random Numbers

Matrix query/Creation functions
These take the following form:

<function>(nRows,nColumns)
    OR
<function>(nRows/Columns) %if square matrix

Random matrices

rand(3,1)          % 3x1 matrix with elements sampled uniform distribution between zero and 1
rand(1,3)          % 1x3 matrix
rand(3,3)          % 3x3 matrix
rand(3)            % 3x3 matrix

Controlling the randomness

rng(3)             % rng sets the random seed
rand(5)            % Note the value here
rand(5)
rng(3)
rand(5)            % The value here should be the same as above

Expanding Rand

Many times you need some regular matrix, but no function exists
No function to sample between -30 & 30 exists
How to get values between -30 & 30?
rand(3,3)*60-30

Tensors
What happens if we do more than 2 dimensions)?
rand(3,3,3) 3D matrix aka tensor
Can’t show a 3d matrix at once, so it shows slices
Showing subscripts of each dimension
’:’ means all elements

Large Outputs and semicolon

rand(100,100,100)           % Should produce a large output
<C-c>                       % Cancels operation
rand(100,100,100);          % Semi-colon supresses output
rand(1000,1000,1000);       % You should get an error about memory limitations
A=rand(100); B=rand(200);   % Semicolon can separate commands on same line

Randi

randi(100,3,2)              % 3x2 matrix with random integers between 1 & 100

Other important

ones()                      % Matrix of just ones
zeros()                     % Matrix of zeros
eye()                       % Identity matrix

Array Summary

Length

A=rand(10,1)
B=rand(1,10)
A=length(A);               % Size of largest dimension
B=length(B);               % Size of largest dimension

Size

size(A)                    % Size of all dimensions
size(A,1)                  % Query dimensions
size(A,2)
numel(A)                   % Number of elements in matrix

sum(A,1)                   % Add all elements accross rows
sum(A,2)                   % Add all elements accross columns
sum(A)                     % Default to sum accross rows (dimension 1), leaving row vector
min(A,[],1)                % Minimum values in rows
max(A,[],2)                % Maximum values in rows
min(A,B,1)                 % Minimum values in rows between A & B
min(A,B,2)                 % Minimum values in columns between A & B

imagesc(A)
colorbar

DO EXCERCISE 8

Binning

Figure 4 - histogram

figure(4)
A=randn(1000,1)          % Normally distributed random numbers
histogram(A)             % Histogram, automatically setting the number of bins
histogram(A,10)          % Set number of bins to 10
help histogram

Figure 5 - bar

figure(5)
counts=[countsA; countsB]
bar(ctrsA,counts')
bar(ctrsA,counts',1)
bar(ctrsA,counts','stacked')
close all                 % Close all figures

figure(5)
plot(ctrsA,countsB,'k')
hold on
plot(ctrsB,countsB,'r')
close all

DO EXCERSISE 9

Conclusion

  • Use matlab/octave as your calculator whenever you can
  • Remember doc & help
  • Google is your best friend
  • Loads of people at your stage who have already asked your questions

What’s in part 2?

  • Tools for building more permanent pipelines - more programming side of things
  • Statistical analysis
  • Any Specific problems - come up and chat

Exercises

1. Operators & functions

  1. Assign variables a,b,c to different integer values
  2. Create an anonymous function of the quadratic equation:

\[ \frac{-b \pm \sqrt{b^2-4ac}}{2a} \]

  1. Consider a,b,c as coefficients in a quadratic equation ax2+bx+c
  2. Find when x=0 using your quadratic equation

Challenge:
Integrate the exponent of cosine of x between 0 and half pi

2. Matrices 1

  1. Create a column vector A with elements 1000 2000 3000
  2. Create a row vector B with elements 4000 5000 6000
  3. Combine the two vectors to create a 2x3 matrix C
  4. Multiply all elements by 2

Challenge:
See if you can identify the differences between functions repelem() and repmat().

3. Strings

  1. Assign variables to the following strings:
    ’Strings’, ’ ’, ’are ’, ’nice’ ’.’
  2. Concatenate the strings in order with a new line between ’Strings’ and ’ ’
  3. Create a second string with your name.

Challenge:

  1. Use strrep() to replace your name with my name
  2. Use strsplit() and join() to rearrange the sentence order

HINT: Cells group arrays of different sizes.
Indexing rules for cells are the same, but use {} instead of () in particular cases.

4. Plotting Basics

  1. Create values of y, where y = tangent(x), with 1000 x values between 80 and 100
    HINT: use the function tan()
  2. Display this plot with the following properties:
    • Triangle points with magenta outline and blue filling (HINT: use help)
    • y limited to -20 and 20
    • Label the x and y axis

Challenge
“For” loops in matlab are written as
for i = r; <command(s)>; end
where r is any valid range eg (1:1000)
See if you can create animate a plot by using a for loop and drawnow()

5. Subplots

Use 1000 x values between 1 and 10 for the following

  1. plot the functions log(x) and sin(x) on the same subplot with ylim 0-2.5
  2. plot the function the square root of ( e to the x ) in a subplot below 1.

After plotting, add a title to the top subplot

Challenge
Make the second subplot twice as wide as the top

6. Plotting 3D

  1. Using surf and imagesc in seperate figures:
    plot the surface 1/x2 + 1/y2 between -3 & 3 for both x and y
  2. Display the colorbar in each
  3. Display the plots between -2 & 2 for both x and y
  4. change the colormap

Challenge
“For” loops in matlab are written as
for i = r; <command(s)>; end
where r is any valid range eg (1:1000)
See if you can create animate a 3d plot by using a for loop and drawnow()

7. Index & Subscripts

  1. Create a random matrix between -10 and 90, with 10 rows and 9 columns.
    HINT: create a matrix with integers values between 0 & 100 first
  2. Select values between the 3rd and 4th column and the 2nd and 6th and set these values equal to 3
  3. Remove the 4th column.
  4. Check the number of columns in the matrix.
  5. Remove the 10th element from the matrix.
  6. Check the size of the matrix again.

Thought for food:
A third type of indexing exists in matlab - logical indexing.
We used this secretly when using basic logic and the find function.
Try this:
A=randi(10,10)
i=A==10
sum(sum(i))
ind=find(i)
numel(ind) %Compare with the sum step above
A(i)
A(i)=3
i=A==10
sum(sum(i)) %Compare with other sum above

8. Matrices 3

  1. Create a random matrix of size 3x2,
  2. Matrix Multiply it by an identity matrix
  3. Element wise multiply by 10
  4. Sum all the Elements (both vertical and horizontal)
  5. Visualize your matrix

Challenge:

  1. Use normrnd() to draw values from a normal distribution of mean 5 and standard deviation 3
  2. Use histogram() to visualize your results

9. Binning

  1. Generate random samples from normally distributed matrix of size 10x2 with mean of -3
  2. Create 3x1 subplots with bins of integers between -10 & 0:
    • histogram of the first column of data
    • histogram of the second column of data
    • histogram of the sum of both columns

Challenge
Repeat this exercise but with hist() and plot in a single subplot.

Answers

1. Operators & functions

a=1;
b=3;
c=5;
p = -b + sqrt(b^2-4*a*c)/(2*a);
% use up arrow
n = -b - sqrt(b^2-4*a*c)/(2*a);

2. Matrices 1

A = [1000; 2000; 3000];
B = [4000, 5000, 6000];
C = [A' B].*2;

3. Strings

A='Strings'
B=' '
C='are '
D='nice'
E='.'
string1=[A newline B C D E];
string2='David White'
cellA={string1, string2}
%OR
cellA{1}=string1;
cellA{2}=string2;

4. Plotting Basics

x=linspace(80,100,1000)
y=tan(x)
plot(x,y,'m<','MarkerFaceColor','b')

5. Subplots

x=linspace(1,10,1000)
figure(1)
subplot(2,1,1)
plot(x,log(x));hold on
plot(x,sin(x));hold off
subplot(2,1,2)
plot(x,sqrt(exp(x)))
subplot(2,1,1)
title('title')

6. Plotting 3D

l=linspace(-3,3,100);
[x,y]=meshgrid(l);
z = 1./x^2 + 1./y^2;
a=subplot(2,1,1)
surf(x,y,z)
b=subplot(2,1,2);
imagesc(z)
colormap(b,winter);

7. Index & Subscripts

A=randi(100,10,9)-10
A(2:6,3:4)=3
A(:,4)=[]
size(A,2) %should be 8
A(1)=[];
size(A);  should be 1x79

8. Matrices 3

sum(sum(rand(3,2).*eye(3,2)*10))
%single digits are treated as scalars, which are always element wise

9. Binning

bins=-10:0
A=randn(100,2)-3
subplot(3,1,1)
histogram(A(:,1),bins)
subplot(3,1,2)
histogram(A(:,2),bins)
subplot(3,1,3)
histogram(sum(A,2),bins)

Author: Dave White

Email: davey@cryptolab.net

Created: 2020-07-25 Sat 14:04