__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

__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__

```
% 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__

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

__Strings__

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

__Logic__

```
=3
b=-3
a> 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?
b 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)
=== b==4 % Assigning result of logical test c
```

__Combined logic__

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

__Workspace variables__

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

__Clutter__

```
<C-c> %<c-C> gets you a new command-line
somelongtexthereclc %Clears display
```

__History__

Press Up and Down to browse history.

Use comments to keep notes of what you are doing.

__Completion__

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

__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)__

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

__Integration__

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

__Getting Help__

Can't remember a function

Tab completion

Google

```
help <function>
doc <function>
```

__DO EXERCISE 1__

__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

__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__

- Things in your current directory (pwd)

- Variables in your workspace

- Command History

- 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

Your path consists of

- Current directory

- 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`

__Manual array construction__

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

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__

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

__Matrix operations vs element wise operations__

```
*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 A
```

__Functions on arrays__

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

__Combining arrays__

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

__DO EXCERCISE 2__

```
1:9 % Range
1:2:9 % Increment by 2
1:2:8 % Non inclusive
=linspace(1,9,10) % 10 values equally spaced between 1 and L
```

```
load('myfunctions')
=linspace(-5,5,1000)
x=f(x)
yplot(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

```
=linspace(1,9,10) % 10 values equally spaced between 1 and 9
Lplot(L,L,'.') % This won't work
```

```
,Y]=meshgrid(L); % This distributes x and y
[Xplot(X,Y,'.k') % This works.
```

We will return to this after we look at some 2D plots, but first 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__

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

__This means we can combine them like matrices__

```
var='eight
=['the variable equals ' var '.'] %Concatenation
stringvar='8'
=['the variable equals ' var '.'] %Concatenation
stringvar=num2str(8)
=['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
string=[filesep 'home' filesep 'dambam' filesep 'test1'] %filesep is similar, but returns os agnostic directory char fname
```

__DO EXERCISE 3__

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

__Note on Continuity__

The function f is continuous with inf inite domain

computers need discrete information

__Discrete plotting__

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

__Increase Resolution__

```
=linspace(1,100,1000) % x values of what is being plotted
x=f(x); % y values of what is being plotted
yplot(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__

```
=@(x) 1./(x.^2)
g=g(x)
zplot(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

__Geneate several functions__

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

__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__

__Plotting a 3D function__

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

__Create Grid__

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

__Plot using Grid__

```
figure(3)
=h(X,Y)
zsize(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

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)

```
=[80 106 32; 90 70 4; 3 1 2]
A1) % 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
A(=A(:) % Matrix to column vector B
```

ind=find(A==90)

```
=[80 106 32; 90 70 4; 3 1 2]
A1,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 A(
```

Trick to remember:

Index - Individual

Subscripts - Begins with s - plural

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

__Editing Matrices__

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

__Deleting values__

size(A)

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

__Combining matrices__

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

__DO EXCERCISE 7__

__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__

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

__Expanding Rand__

```
times you need some regular matrix, but no function exists
Many function to sample between -30 & 30 exists
No get values between -30 & 30?
How to 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
=rand(100); B=rand(200); % Semicolon can separate commands on same line A
```

__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
```

__Length__

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

__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__

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

```
figure(5)
=[countsA; countsB]
countsbar(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__

- 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

- Tools for building more permanent pipelines - more programming side of things

- Statistical analysis

- Any Specific problems - come up and chat

- Assign variables a,b,c to different integer values

- Create an anonymous function of the quadratic equation:

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

- Consider a,b,c as coefficients in a quadratic equation ax
^{2}+bx+c

- Find when x=0 using your quadratic equation

__Challenge:__

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

- Create a column vector A with elements 1000 2000 3000

- Create a row vector B with elements 4000 5000 6000

- Combine the two vectors to create a 2x3 matrix C

- Multiply all elements by 2

__Challenge:__

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

- Assign variables to the following strings:

'Strings', ' ', 'are ', 'nice' '.'

- Concatenate the strings in order with a new line between 'Strings' and ' '

- Create a second string with your name.

__Challenge:__

- Use strrep() to replace your name with my name

- 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.

- Create values of y, where y = tangent(x), with 1000 x values between 80 and 100

HINT: use the function tan()

- 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

- Triangle points with magenta outline and blue filling (HINT: use help)

__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()

Use 1000 x values between 1 and 10 for the following

- plot the functions log(x) and sin(x) on the same subplot with ylim 0-2.5

- 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

- Using surf and imagesc in seperate figures:

plot the surface 1/x^{2}+ 1/y^{2}between -3 & 3 for both x and y

- Display the colorbar in each

- Display the plots between -2 & 2 for both x and y

- 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()

- 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

- Select values between the 3rd and 4th column and the 2nd and 6th and set these values equal to 3

- Remove the 4th column.

- Check the number of columns in the matrix.

- Remove the 10th element from the matrix.

- 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

- Create a random matrix of size 3x2,

- Matrix Multiply it by an identity matrix

- Element wise multiply by 10

- Sum all the Elements (both vertical and horizontal)

- Visualize your matrix

__Challenge:__

- Use normrnd() to draw values from a normal distribution of mean 5 and standard deviation 3

- Use histogram() to visualize your results

- Generate random samples from normally distributed matrix of size 10x2 with mean of -3

- 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

- histogram of the first column of data

__Challenge__

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

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

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

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

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

```
=linspace(1,10,1000)
xfigure(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')
```

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

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

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

```
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)
```