## 1 Elementary Matlab

### 1.1 Intro

Why do you want to use matlab specifically?
other people are using it
one of the easiest to learn
"high level"
no need to compile necessary
matrices

Alternatives:
Julia
R
Python
Ruby

Many principles taught here will apply to other languages

May seem like a lot, but it comes down to just a couple of things
matrices
functions - MANY
a few data-types
number type
characters
Hardest part is remembering functions, optimizing
Recommendation - go home and make a cheat sheet of all the functions we create
Our goal here: get you to use this as a simple calculator whenever you can.
This session only uses the commandline, workspace, and filebrowser

### 1.2 Commandline

Possible Inputs
files
variables
functions
Possible Output
variables (see workspace)
system commands (hidden output)

### 1.3 Notation for this demo

<C-c> specifies control-C
<Tab> tab key
<function> any function

### 1.4 Operators

8+5
8*5 *multiplication
ans + 3
ans is an automatically assigned variable
b=3
b2 exponent
(b+3)/2 order of operations apply!

somelongtexthere<C-c>
<c-C> cleans gets you a new command-line
Press Up and down to browse history
clc Cleans workspace
variableA=1
vari<Tab>2 + b2

### 1.5 Functions

functions require parenthesis
sqrt(5)
b=6
abs(3-b)
mod(10,2)
round(7/2)
floor(7/2)
ceil(7/2)
fix(7/2) rounds to zero

more help on a function:
help <function>
doc <function>
these have links to similar functions you can tab complete to get full name of function you only know beginning of

### 1.6 Matrices

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
can have both

functions typically apply to whole matrices
round(A)

matlab is optimized for matrices/vectors
All inputs and outputs are interpreted as matrices
8 is a 1x1 matrix

### 1.7 Workspace

loaded variables - you can use these variables in another function
round(A)
round(ans)
you can also…
click on them to get more info and edit if not too big try with A

save('somefilename') no error means successfully saved
clear clears all variables from workspace
load('somefilename') restores workspace that was saved
save('somefilename','A') saves only variable A
save('somefilename','A','B') saves only variables A & B
delete('somefilename.mat') no error means deleted
OR
delete('somefilename')
where are we saving to? default is home directory
pwd lists current directory
cd
relative and absolute directories
aboslute begin with a slash in unix
absolute begin with drive then backslash
difference between windows and mac/linux/unix
/Users/dambam mac
/home/dambam unix
C:\Documents\ windows
cd('Code')
ls lists files in current directory
cd('') *'' shortcut for home on linux/mac*
mkdir('longdirectoryname')
cd('longdirectoryname')

why the quoatation?
variables don't have to be numerical, they can be strings
You can also use the file browser for most things

#### 1.7.1 Exercise

In your home directory, create directory test2 inside directory test1.
then save a with the data a='this is a test'
list the contents of the new directory

a='test1/test2'
mkdir(a)
cd(a)

pwd
a='this is a test'
save(filename,variables)
cd('/home/dambam')
cd(~)

#### 1.7.3 Now how do I delete this junk?

must delete file first!
delete('somefilename.mat')
delete('test1/test2/
rmdir('test2')
rmdir('test1')
easy to delete things you don't want to delete -> necessary to have backups!
If using tab completion, but make sure to carefully check before deleting!

plantext/mat files contain data, m files are code
good practice to keep data and code seperate

### 1.8 Matrices Example

[3,3]*[3;3] matrix operations (insides must dimensions match)
[3;3]*[3, 3]
[3 3]*[3, 3]' transpose
[3;3].*[3, 3] element wise
[3;3]./[3, 3] element wise
det([ans;ans]) determinant
if you have matlab
help jacobian
doesn't exist in octave by default
if it doesn't exist in octave by default, chances are you can find a function on github or elsewhere

not super practical to write everything out manually
1:9 - range
1:2:9 - increment
1:2:8 - non inclusive

### 1.9 Indexing

randi(10,5,5)
A=randi(10,5,5)
A(1)
A(1:3)
A(:)
A(1:end)
A(1:end-1)
B=A(:)

indexing runs down clumns then rows:

 1 4 7 2 5 8 3 6 9

### 1.10 Subscripts

A(1:3,1:2)
A(1,:)
A(1:end,:)

subscripts - specifies rows then columns

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

(trick to remember: Index - Individual, subscripts (begins with s - plural)

### 1.11 Vectors Matrices & Tensors

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

some things prefer row vectors to column vectors
1:100 row vector
vs
[1:100]' column vector

random matrices are good for trying things out
rand - sample uniform distribution between zero and 1
rand(3,1)
rand(1,3)
rand(3,3)
rand(3)
how to get values between -30 & 30?
rand(3,3)*60-30
randi(100,3,2)
what happens if we do more than 2)
rand(3,3,3)
can't show a 3d matrix at once, so it shows slices
showing subscripts of each dimension
':' means all elements
rand(100,100,100)
C-c
clc
semi-colon
rand(1000,1000,1000)
maybe trouble on windows!
eye()
ones()
zeros() - very useful later

what is this telling me?
length(zeros(10,1))
length(zeros(1,10)

size(1,2)
numel(zeros(3,3))

sum()
min()
max()
*default to sum accross rows (dimension 1), leaving row vector
sum(A,1)
sum(A)
sum(A,2)

#### 1.11.1 exercise

create a random matrix of size 3x2, matrix multiply it by an identity matrix, then element wise multiply by 10, then sum all the elements

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

### 1.12 Efficiently using matrices and vectors

logicals
loops are slow
find is slow
sets
A=rand(10);
[B,I]=sort(A,1)
sort(sort(A))

A=rand(10);
C=unique(A)
C=unique(A)

A = [5 7 1];
B = [3 1 1];
union(A,B)
sort([unique(A); unique(B)])

intersection
A = [7 1 7 7 4];
B = [7 0 4 4 0];
C = intersect(A,B)

ismember([3 2 1], [2 1 3])

A=[1:8; randi(10,3,8); 1:8;randi(10,3,8)]
B=[ randi(10,4,8); 1:8;randi(10,3,8)]
ismember(A,B,'rows')

### 1.13 Conditional operators

[n,m]=find(A==8)
ind=find(A==8)
[n,m]=find(A==8 & A==4)
ind=find(A==8 | A==4)
A==8 | A==4
logical index - binary operation
find operates on logicals
find([0 8]) -> implicitly converting from double to logical
A(A>2)
A(A>2)=0
B(B>2)=[]

All the operators for logical indexing are
= *equal to* ~ not equal to
& and

 or

> greater than
>= greater than or equal to
< less than
<= less than or equal to

A~=8
3 > 3
3 >= 3
3 >= (3 - 1)
C=randi(10,size(A))
(A < 8 & A>3) | A==1) | C==3
0 == 8 | 5==3 logical type
(A =8 & sum(sum(A))> 3) | [1 2 3; 1 2 3]=[1 1 1; 1 1 1] element wise
[1 2 3; 1 2 3]==[1 1 1; 1 1 1] & [1 0] invalid
matrix row/columnwise functions
default work like sum,min,max (accross rows, leaving row vector)
any()
all()
rand(3)./0 inf
isinf(ans)
isinf(8)
isnan()

### 1.14 Matrix manipulation

A=1:1000;
B=reshape(A,100,10);
size(B)

B=repmat(A,2,1);
size(B)

B=repelem(A,2,3)
size(B)

%WHAT ARE THESE GOOD FOR?
A=rand(10,2)
B=[1.5 2]
C=repmat(B,size(A,1),1);
D=A.*C

### 1.15 Removing elements

a(index)=[]
number of ways to do this
find()
logical index
combined a(a==3)=[]
combined a(a==3,:)=[]

### 1.16 Datatypes

Before we go any further
Numbers by
double most precise, takes up most memory
single half as precise as double
int less preciese as double
int8, int16,…
logical least precise, least amount of memory. Default type when using logical operators
Use double (default) and logical unless you need to save on memory
convert between types using double(), single(), int8(), etc.
Char - just letters or non evaluatable numbers
'a'
'1'
' '
Strings
an array of char
'this is a string' 1x16 row vector

### 1.17 Strings

strcmp()
Strings row vector of char datatype (different than numerical)
var=3;
concatenation string=['the variable equals ' var '.']
this makes sense if strings are vectors of characters
numerically the same as
a=1
b=[2 1]
[a b [1 3 4]]
disp(string)
disp(['the variable equals ' var '.'])
newline or '\n' (backslash, not normal slash)
filesep - OS agnostic
r=input('','s')

### 1.18 Cells

collection of matrices
essential for grouping strings and matrices of different sizes
Don't use unless you have to - makes things complex

C=cell(3,1);
C{1}=A
C{2}=B
C{3}='label'
C{1}(1:3) indexing matrix a, indexed in cell C

try to find a matrix solution when you can
cells can be hard to work with

### 1.19 Plotting

figure
title
x=linspace(1,100,1000)
y=1/x;
plot(x,y,'+')
plot(x,y,':')
plot(x,y,'–')
plot(x,y,'r.')
title

'LineWidth'
'MarkerSize'
'MarkerEdgeColor','b'
'MarkerFaceColor',[.5 .5 .5]

scatter(x,y,'r.')
xlabel ylabel
xlim ylim
legend('Responses')

x=-2:0.25:2;
[X,Y]=meshgrid(x);
z=X.*exp(-X.2-Y.2);
imagesc(z)
colormap winter
colorbar

close

imagesc(X)
axis image
colormap gray
x=linspace(1,500)
y=linspace(1,350)
hold on
plot(x,y,'r')

surf(z)
caxis([0,4])

figure(1)
x=-2:0.25:2;
y1=exp(x)
y2=log(x)
plot(x,y1)
hold on
plot(x,y2)

imshow('board.tif')

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

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

histogram

A=[]
for i = 1:100
A=[A; randn(10,1)]
histogram(A)
drawnow
pause(.1)
end

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
imagesc(B(:,:,1))
drawnow
kk=waitforbuttonpress;
end

### 1.20 Anonymous functions

funA=@(x) exp(-x.2).*log(x).2;
lets x remain unset
funA(linspace(1,10,100))
integral(funA,0,Inf) *integrate using anonymous functions

A=randi(100,20,3)
arrayfun(funA,A)

A=randi(100,20,3)
arrayfun(@(x,y) x.2/3,A)

A=randi(100,20,3)
B=[1 2 3]
bsxfun(@minus, A, B)

### 1.21 Conclusion

Remember doc & help