1 of 46

Programming Basics for Logistics Algorithms:

Review Session

Tatiana Polishchuk

Associate Professor, 

Linköping University, KTS

itn.liu.se/~tatpo46/

1

2 of 46

Course Overview

  • Introduction to programming
  • Variables and data types
  • Algorithms and scripts
  • Input/output statements
  • Conditional statements
  • Loops, nested loops
  • Vectors
  • Matrices and graphs
  • Plotting: graphical functions
  • Good programming practices
  • Data Management

2

3 of 46

3

And finally….

What is Matlab?

Matlab is both a program and a programming language ...

… it has lots of tools you can just use to analyse data and images. But you can also write code to extend it to do any analysis you like (although unlike a ‘pure’ language, it will only work if the Matlab program is installed on the computer).

Excel

Photoshop

Writing your own code

Using other people’s code

+

+

+

=

A really powerful tool for work and research!

4 of 46

Command window

  • A fancy scientific calculator

>> 2+3

>> 2*3

>> 2/3

>> 2^3

>> 2^0.5

>> 2+3*6/2

>>(2+3)*6/2

  • + check for more complicated math functions: sqrt, power, mod, abs

4

Any of the text in blue is code you can run in the command window. Try copy and pasting, then hitting return

5 of 46

Matlab help commands

  • help

>> help sin - displays documentation for the function sin

  • doc

>> doc sin - opens Matlab documentation

  • lookfor

>> lookfor convert - displays functions with convert in the first help line

  • start Matlab help documentation

>> helpdesk

>> doc

5

6 of 46

Variables and Data Types

6

Data type = class

7 of 46

Workspace

  • Display contents of workspace

>> whos

Name Size Bytes Class

a 1x1 8 double array

b 1x1 8 double array

c 1x1 8 double array

Grand total is 3 elements using 24 bytes

  • Delete variable(s) from workspace

>> clear a b; % delete a and b from workspace

>> whos

>> clear all; % delete all variables from workspace

>> whos

7

8 of 46

Variables and Data Types

8

>> default: double

Casting – converting to other type

>> x = 6+3 >> whos

>> x1 = int32(x) x 1x1 8 double

x1 1X1 4 int32

9 of 46

Variable, script and function names

  • Must start with a letter
  • Followed by any number of letters, digits, or underscores.
  • Matlab is Case Sensitive
    • A and a, my_fun and My_fun, etc are not the same name
  • Be expressive: try and use names that
    • Describe what functions do
    • Describe what variables are

9

10 of 46

Scripts

  • Matlab editor
  • Use scripts to execute a series of Matlab commands

10

Press + to create new m-file in the matlab editor

Press Run button to run the script

11 of 46

Comments

  • Anything following the % sign is interpreted as a comment

>> % This is my first script: LAB1, day 1

>> a = 10; % the number of passengers in the bus

11

12 of 46

12

Hello world! This is my first Matlab script!

Input/Output

>> disp (‘Hello world!’)

Displays the string in parentheses

Remember to put text into ‘ ’

Exercise:

13 of 46

13

Input/Output

>> a = input (‘What is your name? >’)

Expects user’s response and assigns the expression as a value to the variable a

Exercise:

Add to your helloWorld.m script the following lines:

>> myname=input('What is your name?>', 's’);

>> disp ('Written by ')

>> disp (myname)

14 of 46

14

Input/Output

>> a = input (‘What is your name? >’)

Expects user’s response and assigns the expression as a value to the variable a

Exercise:

Add to your helloWorld.m script the following lines:

>> myname=input('What is your name?>', 's’);

>> disp ('Written by ')

>> disp (myname)

Use when you expect a string

15 of 46

15

Input/Output

Formatted output can be printed to the screen using the fprintf function (all in one line! unlike disp)

>> fprintf('The value is %d, for sure!', 4^3)

The value is 64, for sure!

Conversion character:

%d integer (it stands for decimal integer)

%f float (real number)

%c single character

%s string

integer number

place holder

for integer number

16 of 46

16

Input/Output

\n - provides printing from new line

>> fprintf('The value is %d, \n for sure!', 4^3)

The value is 64,

for sure! >>

More escape characters:

\b Backspace '' Single quotation mark

\f Form feed %% Percent character

\t Horizontal tab \\ Backslash

\r Carriage return \N Octal number N

new line

17 of 46

Questions?

Next: Flow control

17

18 of 46

if/else/elseif

18

  • Basic flow-control, common to all languages
  • MATLAB syntax is somewhat unique

IF

if cond

commands end

ELSE

if cond

commands1 else

commands2 end

ELSEIF

if cond1

commands1 elseif cond2

commands2 else

commands3 end

Conditional statement: evaluates to true or false

  • No need for parentheses: command blocks are between reserved words

19 of 46

Relational Operators

19

  • MATLAB uses mostly standard relational operators
  • equal

==

  • not equal

~=

  • greater than

>

  • less than

<

short-circuit (scalars)

&

|

  • greater or equal >=
  • less or equal <=
  • Logical operators elementwise

&&

||

  • And
  • Or
  • Not
  • Xor
  • All true
  • Any true

~

xor all any

  • Boolean values: zero is false, nonzero is true
  • See help for a detailed list of operators

20 of 46

for

20

for

n=1:100

commands

end

  • for loops: use for a known number of iterations
  • MATLAB syntax:

Loop variable

for i = range commands

end

  • The loop variable
    • Is defined as a vector
    • Is a scalar within the command block
    • Does not have to have consecutive values (but it's usually cleaner if they're consecutive)
  • The command block
    • Anything between the for line and the end

21 of 46

for

21

Print ‘Hello world’ 10 times with numbering the lines, each line in new row

>>

Hello world 1

Hello world 2

Hello world 3

Hello world 4

Hello world 5

Hello world 6

Hello world 7

Hello world 8

Hello world 9

Hello world 10

22 of 46

for

22

Print ‘Hello world’ 5 times with numbering the lines, for odd numbers only, starting from 1, each line in new row

>>

Hello world 1

Hello world 3

Hello world 5

Hello world 7

Hello world 9

step = 2

23 of 46

while

23

  • The while is like a more general for loop:
    • No need to know number of iterations

WHILE

while cond commands

end

  • The command block will execute while the conditional expression is true
  • Beware of infinite loops! CTRL+C?!

24 of 46

24

>>

i =

4

i =

16

i =

256

Without ; to print output

while

Step by step:

iteration 0: i = 2

Iteration 1: check (2<100)

i = 2*2= 4

Iteration 2: check (4<100)

i = 4*4 = 16

Iteration 3: check (16<100)

i = 16*16 = 256

Iteration 4: check (256>100)

exit

25 of 46

Questions?

Next: Arrays

25

26 of 46

1D Arrays: vectors

  • Creating
    • Explicitly:
      • a = [1 2 3 4]; a = [1; 2; 3; 4]; a = [0.2 3 2.7]
    • Using the ‘:’ operator:
      • a = 1:4; a = 4:1; a = 4:-1:1; a = 1:10:40; a=0:0.2:1;
    • Using ‘ones’ or ‘zeros’
      • a = ones(5,1); a = ones(1,5); a = zeros(10,1);
    • Using random sampling functions ‘rand’, ‘randn’
      • a = rand(5,1); a = randn(5,1); a = randi(5,5,1)

26

27 of 46

1D Arrays: vectors

27

More examples how to create vectors:

>> a = [1 2 3 4]

>> a = [1, 2, 3, 4]

>> a = 1:4 % no need for []

>> b = 1:2:9

b =

1 3 5 7 9

>> ? how to define the vector c:

9 7 5 3 1

28 of 46

1D Arrays: Indexing and

accessing elements

28

Indexing vectors: starting from “1”

>> newvector=[1 3 5 7 9 3 6 9 12 15]

Accessing elements of the vector: vector(index) or vector(index vector)

>> newvector(3)

ans = 5

>> newvector(4:6)

ans = 7 9 3

>> newvector([1 10 5])

ans = 1 15 9 index vector

first element

29 of 46

1D Arrays: Concatenation

29

Add elements to the empty vector

>> myvector=[]

>> myvector = [myvector 4]

ans=

4� >> myvector = [myvector 2]

ans=

4 2

Can be continued as many times as needed!

30 of 46

2D Arrays: Matrices

30

>> A = zeros (5,5)

A =

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

>> B = ones (3,4)

B =

1 1 1 1

1 1 1 1

1 1 1 1

>> C = rand (2,3)

C =

0.5504 0.0791 0.8982

0.5963 0.5766 0.4633

>> D = randi (10, 2,3)

D =

10 2 9

7 4 6

range

31 of 46

Matrix Modification

31

Modifying matrix elements assigning a new value:

EXAMPLE:

A = 3 3 4 7 A(1,2)= 13 3 13 4 7

5 3 2 1 5 3 2 1

2 3 2 1 2 3 2 1

1 3 1 1 1 3 1 1

A = 3 3 4 7 A(:,4)= [ 5; 5; 5; 5] 3 13 4 5

5 3 2 1 5 3 1 5

2 3 2 1 2 3 2 5

1 3 1 1 1 3 1 5

32 of 46

Removing Elements from Matrix

32

It is not possible to remove just 1 element to the matrix!

But we can remove entire rows or columns:

EXAMPLE:

A = 3 3 4 4 A(3, : )= [ ] A = 3 13 4 4

5 3 2 4 5 3 2 4

2 3 2 3 1 3 1 1

1 3 1 1

B = 1 2 1 B (4) = [ ] B = 1 1 1 1 1 1 1 1

1 1 1 reshaping

1 1 1

33 of 46

Size, Length and Numel

  • Size function returns the vector [#rows, #columns]:

A =

10 2 9

7 4 6

  • Length function returns either # rows, or #columns, whichever is largest:

>> length(A) =

ans =

3

  • Numel function returns the total number of elements in the array

>> numel(A) =

ans =

6

33

>> size(A)

ans =

2 3

34 of 46

Vector & Matrix Algebra

IMPORTANT: there are two types of matrix operations

  • linear algebra operations

  • element-wise operations

34

35 of 46

Element-wise functions

Element-wise operations

35

Pay attention to which mode you mean to use!

36 of 46

Summary

  • Understanding how arrays work is the key to successful programming
  • [] – square brackets create new arrays
  • () – access parts of an array
  • *,^ etc. perform linear algebra (matrix) operations
  • .*,.^ etc. perform element-wise operations

Quiz from previous lecture: Arrays and Matrices

36

MATLAB makes arrays easy!

That’s its power!

37 of 46

Next: Graphs

37

Questions?

38 of 46

Graphs

  • A graph is a pair (V, E), where
    • V is a set of nodes, called vertices
    • E is a collection of pairs of vertices, called edges
    • Vertices and edges are positions and store elements
  • Example:
    • A vertex represents an airport and stores the three-letter airport code
    • An edge represents a flight route between two airports and stores the mileage of the route

38

ORD

PVD

MIA

DFW

SFO

LAX

LGA

HNL

849

802

1387

1743

1843

1099

1120

1233

337

2555

142

39 of 46

Operations on Graphs

  • What operations do you think we can do to a graph
    • add an edge
    • add a node
  • Others……

39

40 of 46

Representation

  • There are different ways to represent a graph
  • List of edges
  • Adjacency matrix

40

41 of 46

41

42 of 46

42

43 of 46

Visualizing Graphs

digraph objects represent directed graphs, which have directional edges connecting the nodes

>>clear ;

>>A = [

0 1 0 1;

1 0 1 0;

0 1 0 1;

1 0 1 0

];

>>figure;

>>G = digraph (A);

>>plot (G);

43

44 of 46

Visualizing Graphs

Defining edge list - another way of creating graphs

>> E_list = [

1 2;

1, 3;

2, 3

]; % edge list

>> E_weights = [1 1 2];

>> G = graph(E_list(:,1), E_list(:,2), E_weights);

>> plot (G)

44

45 of 46

Visualizing Graphs

graph objects represent undirected graphs, which have direction-less edges connecting the nodes

>>clear ;

>>A = [

0 1 0 1;

1 0 1 0;

0 1 0 1;

1 0 1 0

];

>>figure;

>>G = graph (A);

>>plot (G);

Graph created using adjacency matrix

45

46 of 46

Questions?

Thank you!

46