## Table of Contents

- 1. Elementary Matlab
- 1.1. Notation for this demo
- 1.2. Intro
- 1.3. Operators
- 1.4. Functions
- 1.5. Workspace
- 1.6. Matrices
- 1.7. Matrices Example
- 1.8. Indexing
- 1.9. Subscripts
- 1.10. Vectors Matrices & Tensors
- 1.11. Logic
- 1.12. Sets
- 1.13. Matrix manipulation
- 1.14. Datatypes
- 1.15. Strings
- 1.16. Plotting
- 1.17. Grouping
- 1.18. Anonymous functions
- 1.19. Conclusion
- 1.20. Next time

- 2. Exercises
- 3. Answers

## 1 Elementary Matlab

### 1.1 Notation for this demo

<C-c> specifies control-C

<Tab> tab key

<function> any function

### 1.2 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

Some things to consider;

not free

not open/free

bulky

not flexible

Alternative "high level" languages:

Python - numpy - uses the same code base for matrices

R

Julia

Ruby

Personally like them better, because they succeed where matlab fails

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

operators - about a dozen

functions - MANY

a few data-types

number type

characters

Hardest part is remembering functions

This is posted online on my website.

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

%matlab works a lot like a scientific/graphic calculator

8+5 %+ is an operator

8*5 %multiplication

%Anything after a percent sign is a comment - it will not be evaluated

ans + 3

%ans is an automatically assigned variable

b=3

b^{2} %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} + b^{2}

%tab autocompletes variables shown in your workspace

### 1.4 Functions

sqrt(5)

*functions have parentheses

b=6

abs(3-b)

*inputs can be simplified before being evaluated in functions

mod(10,2)

*multiple inputs seperated by a commma

*several variations on rounding

round(7/2) %normal rounding

floor(7/2) %round down

ceil(7/2) %round up

fix(7/2) %round towards 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.5 Workspace

%you can also…

<click on A in workspace> %get more info and edit if not too big

save('fname') %no error means successfully saved

clear %clears all variables from workspace

load('fname') %restores workspace that was saved

save('fname1','a','b') %saves only variables A & B

load('fname1')

clear

load('fname')

where are we saving to? default is home directory

pwd %lists current directory

ls %lists files in current directory

mkdir('test1')

cd('tes<Tab>') %You can autocomplete files that are in your path

cd('test1')

save('fname2')

cd('`') %'`

' shortcut for home on linux/mac

cd('..') %double dots is back a directory

load('fname2') %doesn't work

%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

%why the quoatation?

%non-quotations are read as variables.

%quotations are read as strings

%variables don't have to be numerical, they can be strings

S='/home/dambam/test1'

cd(S)

%You can also use the file browser for most things

%.m file extension specify scripts and functions (plaintext format)

%.mat specifies data (binary format)

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

round(A)

%functions typically apply to whole matrices

%matlab is optimized for matrices/vectors

%All inputs and outputs are interpreted as matrices

%8 is a 1x1 matrix

%loaded variables - you can use these variables in another function

round(A)

round(ans)

### 1.7 Matrices Example

A=[3,1]

B=[2,4]

A+B %matrix addition

A-B %subtraction

A*B %matrix multiplication (in linear algebra, matrices are like functions. Matrix multiplication is like combining to [linear] functions)

A*B %matrix operations (insides must dimensions match)

A*A' %transpose

A.*B %element wise

A./B %element wise

C=[A,B]

C=[A;B]

det(C) %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

L=linspace(1,9,10) %10 values equally spaced between 1 and 9

meshgrid(L,L)

### 1.8 Indexing

A=rand(10) %random integers between 1 & 10, in a 5x5 matrix)

%we want to access only certain parts of this matrix

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

%indexing runs down columns then rows:

1 | 4 | 7 |

2 | 5 | 8 |

3 | 6 | 9 |

### 1.9 Subscripts

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,:) %everything but the first row

*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.10 Vectors Matrices & Tensors

%Many functions exist to create matrices, alter matrices, or query matrix properties

%These take the following form:

<function>(nRows,nColumns)

OR

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

%random matrices are good for trying things out

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

%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

%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 dimensio

%':' means all elements

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

%maybe trouble on windows!

%semicolon can also be used to separate commands and run them on the same line

A=rand(100); B=rand(200);

%Some other useful functions

eye() %identity matrix

ones() %matrix of just ones

zeros() %matrix of zeros

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

%what is this telling me?

length(zeros(10,1)); %size of largest dimension

length(zeros(1,10); %size of largest dimension

size(1,2) %size of all dimensions

numel(zeros(3,3)) %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

### 1.11 Logic

2>1 %1 is equivalent to true

2<1 %0 is equivalent to false

2==2

2~=2

%All the operators for logical indexing are

```
= %equal to
~
```

%not equal to

> %greater than

>= %greater than or equal to

< %less than

<= %less than or equal to

& %and

%or |

%Compound statements can be created with & and |

A=2;

B=1;

A>B | A<3 %or

A>B & B<(A+4) %and

(A>-3 | A<3) & B==1; %Group with parentheses

[A A] ```
= [B 2]; %works element wise in matrices
[1 2 3; 1 2 3]=
```

[1 1; 1 1] %invalid

%output when from matrices are called "logical indices"

A=randi(10,10)

I=A>4

A(I) %returns everything that has a 1 logical index

A(A>2)=0 %sets everything that has a 1 logical index to have a value of 0

A(A==0)=[] %removes elements that have a 1 logical index

%NOTE: Removing and setting values matrix values also works with regular indexing and subscripting

A=randi(10,10)

ind=find(A==8) %Get regular index from logical index

A(ind)

[n,m]=find(A==8) %get subscripts from logical index

A(n,m)

%Note the form for functions with multiple outputs

[n,m]=find(A<8 & A>4)

ind=find(A==8 | A==4)

find([0 8]) %simple way of finding index of that are not zeros

~[0 1 1 1 0] %flip 0s to 1s and 1s to 0s

find([~0 8]) %find all zero elements

%Other very useful functions

any(A>1) %check if any of the logical indices in a dimension are 1

all() %checks if all logical indices are 1

rand(3)./0 %infinity

isinf(ans) %checks if values are infinity

isinf(8)

### 1.12 Sets

%Treating matrix elements across a dimension like part of a set

A=rand(10);

B=sort(A,1); %sort across rows

C=unique(A); %All elements in A without repeats

A = [5 7 1];

B = [3 1 1];

union(A,B) %All elements in A and B without repeats

unique([A B]) %All elements in A and B without repeats

C = intersect(A,B) %elements that are present in both A and B

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

D=randi(10,1,8);

E=randi(10,1,8);

F=randi(10,1,8);

G=randi(10,1,8);

X=1:8

A=[X; D; X; E]

B=[F; X; G; X]

ismember(A,B,'rows') %rows that are present in both A and B

### 1.13 Matrix manipulation

A=1:1000;

B=reshape(A,100,10); %reshape 1x1000 to 100 x 10, number of elements need to remain the same

size(B)

A=randi(10,2);

B=repmat(A,2,1) %Duplicates a matrix and appends it to the first dimension

size(B);

B=repmat(A,3,2) %Duplicates a matrix and appends it to 5 times to the first dimension & 2 times to the 2nd

size(B);

A=randi(10,3)

B=repelem(A,2,3) %Duplicates each element in place by specified dimensions

%WHAT ARE THESE GOOD FOR?

%row-wise multiplication

A=randi(10,3,2)

B=[1.5 2]

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

D=A.*C;

### 1.14 Datatypes

%Before we go any further

%Everything is a matrix, but the elements take on specific types

Numbers :

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'

' '

%99% of the time only double, logical, and char are used

### 1.15 Strings

%Strings are not a datatype! They are an array of char

A='this is a string'

size(A)

%This means we can combine them like matrices

var='8'

string=['the variable equals ' var '.'] %concatenation

string=['the variable ''var'' equals ' var '.'] %literal quotations

%numerically the same as

a=1

b=[2 1]

[a b [1 3 4]]

disp(string) %print string

disp(['the variable equals ' var '.']) %print string

[ 'number' num2str(80000) '.']

newline %newline character

fname=[filesep 'home' filesep 'dambam' filesep 'test1'] %OS agnostic slash

r=input('Is matlab fun? ','s') %prompt for input

### 1.16 Plotting

figure(1) %initiates figure 1

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

y=1./x; %y values of what is being plotted

plot(x,y) %plot - by default uses connected line

plot(x,y,'+') %plot unconnected plus siges

plot(x,y,':') %plot connected dots

plot(x,y,'–') %plot connected dashed lines

plot(x,y,'r.') %plot red points

%check out all the different shapes and color with help plot

title('1/x') %create title

plot(x,y,'r.','MarkerSize',10) %change size of markers

plot(x,y,'r','LineWidth',10) %change size of connecting line

plot(x,y,'ro','MarkerEdgeColor','b') %change collor of marker edge

plot(x,y,'ro','MarkerEdgeColor','b','MarkerFaceColor',[.5 .6 .2]) %change edge and face colors, the latter using RBG values

%field, then value

xlabel('x') %label x axis

ylabel('y') %label y axis

xlim([0 40]) %set x axis limits

ylim([0 .4]) %set y axis limits

legend('Responses') %add legend with label 'Responses'

z=1./(x.^{2})

plot(x,z) %erases what we've done

plot(x,y)

hold on %specifies that you don't want to redraw plot

plot(x,z)

legend('Responses1','Responses2') %add legend with 2 labels

hold off

figure(2)

x=-2:0.25:2;

[X,Y]=meshgrid(x); %2D equivalent of linspace: creating X and Y values that will be evaluated along Z

z=X.*exp(-X.^{2}-Y.^{2});

imagesc(z) %third dimension is represented by color

colorbar

colormap winter

help graph3d

colorbar

close %close current figure

surf(z) %third dimension is represented by color and space

%Different ways of displaying images

imshow('board.tif')

open()

load spine

imagesc(X)

colormap gray

axis image

figure(1)

x=-2:0.25:2;

y1=exp(x)

y2=log(x)

y3=abs(x)

y4=x.^{2}

%Plot multiple things seperately in one figure

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)

%You can return to a specific subplot whenever you like

subplot(2,3,2)

ylim([-3 1])

figure(2)

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

close all %close all figures

### 1.17 Grouping

%Cells are a collection of matrices

%Essential for grouping strings and matrices of different sizes

%Don't use unless you have to - rules for cell manipulation can be tricky!

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

%Structs allow for more organization

C=struct()

C.varA=A; %Aname is called the fieldname'

C.B=B;

C.string1='label'

C.D.A=A;

fieldnames(C) %returns all fieldnames belonging to struct C

%Even more organization with classes and objects - a bit more complex

### 1.18 Anonymous functions

%Last random bit

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

### 1.19 Conclusion

Remember doc & help

Google is your best friend

loads of people at your stage who have already asked your questions

"matlab move zero elements from matrix"

Matlab/Octave is one of the easiest languages to begin with

Use matlab/octave as your calculator whenever you can

### 1.20 Next time

Scripts & Functions

Conditional statements

Loops

Debugging and Error handling

Stats

Misc.

If you already know a language - could be boring

Check out my website instead

## 2 Exercises

### 2.1 1. Files

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

return to your home directory

### 2.2 2. Matrices

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

### 2.3 3. Index & Subscripts

Create a random matrix of integers between -10 and 90, with 10 rows and 9 columns.

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.

### 2.4 4. Matrix manipulation

Create a column vector with values 3 through 1502, incrementing by 1.5

Resize the vector to be a matrix of size 20x50

Duplicate all elements in place by 3 columns and 2 row

Remove the fourth column

### 2.5 5. Logical indexing

Create a matrix of size 10x12 with random integers between 5 & 15

Set all values of 10 equal to 4

Add 1 to all values greater than 10

Get subscripts of all values equal to 8

### 2.6 6. Strings

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.

Add these two strings to a cell

### 2.7 7. Plotting

create an anonymous function for 1/x^{2} + 1/y^{2}

generate 3000 z values between -3 and 3 for both x and y

Using 2 different plotting functions in 2 subplots

plot a 3D surface

display the colorbar

change the colormap

## 3 Answers

### 3.1 1. Files

a='test1/test2'

mkdir(a)

cd(a)

pwd

a='this is a test'

save(filename,variables)

cd('/home/dambam')

cd(~)

#### 3.1.1 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

### 3.2 2. Matrices

sum(sum(rand(3,2)*eye(2,3)*10))

%single digits are treated as scalars, which are always element wise

### 3.3 3. 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

### 3.4 4. Matrix Manipulation

A=[5:1.5:3202]';

A=resize(A,4,533);

A=repelem(A,2,3):

A(:,4)=[];

### 3.5 5. Logical indexing

A=randi(10,10,12)+5;

A(A==4)=4;

i=(A>10);

A(i)=A(i)+1;

[n,m]=find(A==8)

### 3.6 6. 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;

### 3.7 7. Plotting

funA = @(x,y) 1./x^{2} + 1./x^{2};

l=linspace(3000,-3,3);

[X,Y]=meshgrid(l);

Z=funA(X,Y);

subplot(2,1,1)

surf(X,Y,Z)

subplot(2,1,2)

imagesc(X,Y,Z)