1 of 60

Programming Basics for Logistics Algorithms: Lecture 4

Tatiana Polishchuk

Associate Professor, 

Linköping University, KTS

www.itn.liu.se/~tatpo46/

1

2 of 60

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 60

Course Overview

3

  • 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

4 of 60

Flashback: Lecture 3

4

5 of 60

2D Arrays: Matrices

5

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

6 of 60

Matrix Indexing

6

  • Matrices can be indexed in two ways
    • using subscripts (row and column)
    • using linear indices (as if matrix is a vector)
  • Matrix indexing: subscripts or linear indexing

b(1)

b(2)

b(3)

b(4)

b(1,1)

b(1,2)

b(1,1)

b(2,1)

b(1,2)

b(2,2)

7 of 60

Adding Elements to Matrix

7

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

But we can add entire rows or columns:

EXAMPLE:

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

5 3 2 5 3 2 1

2 3 2 2 3 2 1

1 3 1 1 3 1 1

A = 3 3 4 A(:,5)= [1,1,1,1]’ 3 13 4 0 1

5 3 2 5 3 2 0 1

2 3 2 2 3 2 0 1

1 3 1 1 3 1 0 1

8 of 60

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

8

>> size(A)

ans =

2 3

9 of 60

Operators

Matrix Operations

9

=

10 of 60

Element-wise functions

Element-wise operations

10

Pay attention to which mode you mean to use!

11 of 60

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

11

ORD

PVD

MIA

DFW

SFO

LAX

LGA

HNL

849

802

1387

1743

1843

1099

1120

1233

337

2555

142

12 of 60

Implementing a Graph

  • To program a graph data structure, what information would we need to store?
    • For each vertex?
    • For each edge?

12

X

U

V

W

Z

Y

a

c

b

e

d

f

g

h

i

j

13 of 60

13

14 of 60

14

15 of 60

Next: Plotting

15

Questions?

16 of 60

Image Processing using Matlab

16

17 of 60

Plotting

17

  • Plot values against their index

» plot(y);

  • Usually we want to plot y versus x

» plot(x,y);

Example: plotting a point

x = 11;

y = 18;

plot(x,y,'r*')

18 of 60

Plotting

18

x = 11;

y = 18;

plot(x,y,'r*')

xlabel('Time')

ylabel('Temperature')

title('Time and Temp')

19 of 60

Plotting

19

x = 11;

y = 18;

plot(x,y,'r*')

xlabel('Time')

ylabel('Temperature')

title('Time and Temp')

axis([x-2 x+2 y-5 y+5])

20 of 60

Plotting a line

20

  • Plotting a straight line

» x = 1:10

» y = 2*x

» plot (x,y)

MATLAB makes visualizing data fun and easy!

21 of 60

Plot Options

21

  • Can change the line color, marker style, and line style by adding a string argument

  • Can plot without connecting the dots by omitting line style argument

  • Look at help plot for a full list of colors, markers, and line styles

22 of 60

More plotting options

22

Colors Plot symbols Line types

23 of 60

More Plot Controls

23

Axis control:

axis - Control axis scaling and appearance

zoom - Zoom in and out on a 2-D plot

grid - Grid lines

box - Axis box

rbbox - Rubberband box

hold - Hold current graph (hold on, hold off options)

axes - Create axes in arbitrary positions

subplot - Create axes in tiled positions

Graph annotation:

title - Graph title

xlabel - X-axis label

ylabel - Y-axis label

texlabel - Produces the TeX format from a character string

text - Text annotation

gtext - Place text with mouse

24 of 60

Playing with the Plot

24

to select lines and delete or change properties

to zoom in/out

to slide the plot around

to see all plot tools at once

25 of 60

Copy/Paste Figures

25

  • Figures can be pasted into other apps (word, ppt, etc)
  • Edit→ copy options→ figure copy template
    • Change font sizes, line properties; presets for word and ppt
  • Edit→ copy figure to copy figure
  • Paste into document of interest

26 of 60

Saving Figures

26

  • Figures can be saved in many formats. The common ones are:

.fig preserves all information

.bmp uncompressed image

.eps high-quality scaleable format

.pdf compressed image

27 of 60

3D Line Plots

27

  • We can plot in 3 dimensions just as easily as in 2D

» t=0:0.001:4*pi;

» x = sin(t);

» y = cos(t);

» plot3(x,y,t,'k','LineWidth',2);

  • Use tools on figure to rotate it

  • Can set limits on all 3 axes

» xlim, ylim, zlim

28 of 60

Surface Plots

28

  • It is more common to visualize surfaces in 3D

  • Example:

  • surf puts vertices at specified points in space x,y,z, and connects all the vertices to make a surface

  • The vertices can be denoted by matrices X,Y,Z

  • How can we make these matrices
    • built-in function: meshgrid

29 of 60

Visualizing matrices

29

  • Any matrix can be visualized as an image

» mat = reshape (1:10000,100,100);

» imagesc (mat);

» colorbar

  • imagesc automatically scales the values to span the entire colormap

  • Can set limits for the color axis (analogous to xlim, ylim)

» caxis ([3000 7000])

30 of 60

surf

30

  • Make the x and y vectors

» x = -pi:0.1:pi;

» y = -pi:0.1:pi;

  • Use meshgrid to make matrices

» [X,Y] = meshgrid (x,y);

To get function values, evaluate the matrices

» Z = sin(X) .*cos(Y);

  • Plot the surface

» surf (X,Y,Z)

» surf(X,Y,Z);

)

rane

*Try typing surf(memb

31 of 60

surf Options

31

faceted

flat

See help surf for more options

There are three types of surface shading

» shading facetad

» shading flat

» shading

  • You can also change the colormap

» colormap (grey)

35

35

interp

flat

32 of 60

contour

32

  • You can make surfaces two-dimensional by using contour

» contour (X,Y,Z, ‘LineWidth’, 2)

    • takes same arguments as surf
    • color indicates height
    • can modify linestyle properties
    • can set colormap

» hold on

» mesh (X,Y,Z)

33 of 60

Specialized Plotting Functions

33

  • MATLAB has a lot of specialized plotting functions
  • polar-to make polar plots

» polar (0:0.01:2*pi, cos ((0:0.01:2*pi)*2));

  • bar-to make bar graphs

» bar (1:10, rand(1,10));

  • quiver-to add velocity vectors to a plot

» [X,Y] = meshgrid (1:10,1:10);

» quiver(X,Y, rand(10),rand(10));

  • stairs-plot piecewise constant functions

» stairs(1:10, rand(1,10));

  • fill-draws and fills a polygon with specified vertices

» fill ([0 1 0.5], [0 0 1], ‘r’);

  • see help on these functions for syntax
  • doc specgraph – for a complete list

34 of 60

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

34

35 of 60

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

35

36 of 60

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

36

37 of 60

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

% to add labels to the nodes:

G.Nodes.Name = { 'Olle ' 'Sara ' 'Karl ' }';

% to mark weights on the graph:

plot (G );

37

38 of 60

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

% to add labels to the nodes:

G.Nodes.Name = { 'Olle ' 'Sara ' 'Karl ' }';

% OR: to mark weights on the graph:

plot (G , 'EdgeLabel', G.Edges.Weight);

38

39 of 60

Questionnaire

39

40 of 60

Next: Data Management

40

Questions?

41 of 60

41

File Operations

  • Read from the file: extract data from files

  • Write to the file: write data to the file starting from the very beginning

  • Append to the file: write data to the file, adding information to what is already there

  • Display content of the file:show file content

42 of 60

42

Read from the file

  • Read from the file: extract data from the file

load filename

  • assigns file content to the array filename
  • use files with extensions .dat, .txt, .mat, etc.
  • only with the data of the same format!
  • only data in matrix format (same number of elements in each row)

43 of 60

43

File Operations

  • Write to the file: write data to the file starting from the very beginning

save filename matrixname -ascii

  • creates file filename
  • uses file extensions .txt, .dat, ect.
  • .mat used to store variables from your workspace
  • writes the data from array matrixname
  • if file not empty -- overwrites the data!!
  • ‘-ascii’ provides correct data format

44 of 60

44

File Operations

  • Append to the file: write data to the file, adding information to what is already there

save filename matrixname -ascii -append

  • adds the data from array matrixname to the end of file filename

45 of 60

45

File Operations

  • Display content of the file: show file content

type filename

Example:

» type testfile.dat

2 4 6 1 0 0 4

2 3 4 1 2 3 4

1 1 2 3 4 5 1

1 2 5 6 2 3 5

46 of 60

46

File Operations

Example: delete the first column from the matrix in file testfile.dat

» type testfile.dat

2 4 6 1 0 0 4

2 3 4 1 2 3 4

1 1 2 3 4 5 1

1 2 5 6 2 3 5

» load testfile.dat

» testfile(:,1) = []; % to delete first column in the matrix

» save testfile.dat testfile -ascii

» type testfile.dat

4.0000000e+00 6.0000000e+00 1.0000000e+00 0.0000000e+00 0.0000000e+00 4.0000000e+00

3.0000000e+00 4.0000000e+00 1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00

1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00 5.0000000e+00 1.0000000e+00

2.0000000e+00 5.0000000e+00 6.0000000e+00 2.0000000e+00 3.0000000e+00 5.0000000e+00

47 of 60

47

File Operations

Example: delete the first column from the matrix in file testfile.dat

» type testfile.dat

4.0000000e+00 6.0000000e+00 1.0000000e+00 0.0000000e+00 0.0000000e+00 4.0000000e+00

3.0000000e+00 4.0000000e+00 1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00

1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00 5.0000000e+00 1.0000000e+00

2.0000000e+00 5.0000000e+00 6.0000000e+00 2.0000000e+00 3.0000000e+00 5.0000000e+00

» testfile = int8(testfile)

testfile =

4×6 int8 matrix

4 6 1 0 0 4

3 4 1 2 3 4

1 2 3 4 5 1

2 5 6 2 3 5

>> save testfile.dat testfile -ascii

Warning: Attempt to write an unsupported data type to an ASCII file.

Variable 'testfile' not written to file.

48 of 60

48

Advanced File Operations

  • Low-level I/O functions to work with different file formats

fopen, fclose, fscanf, textscan, fgetln, xlsread

fread, fwrite, fseek, and frewind, and more...

Some examples:

https://www.mathworks.com/help/matlab/learn_matlab/data-analysis.html

https://www.mathworks.com/help/matlab/examples.html?category=data-import-and-analysis

https://www.mathworks.com/help/matlab/import_export/add_spreadsheet_data_arrays_variables.html

49 of 60

49

Advanced File Operations

  • Read table of mixed data types

T = readtable(filename)

  • creates a table T by reading column oriented data from a file
  • determines the file format from the file extension:

.txt, .dat, or .csv for delimited text files

.xls, .xlsb, .xlsm, .xlsx, .xltm, .xltx, or .ods for spreadsheet files

  • creates one variable in T for each column in the file and reads variable names from the first row of the file
  • by default, creates variables that have data types that are appropriate for the data values detected in each column of the input file

50 of 60

50

Advanced File Operations

  • Read table of mixed data types

T = readtable(filename)

  • To access variables representing columns of the table:

T.columnname

  • Write of different data types to a file

writetable(T, filename)

51 of 60

51

Cell Arrays

  • Elements in cell arrays are containters that can store different types of values

  • stores pointers do different data
  • unique data structure for Matlab
  • use {} to create such arrays

Example:

» cellrowvec = {23, 'a', 1:2:9, 'hello'}

cellrowvec =

[23] 'a' [1x5 double] 'hello'

52 of 60

52

Cell Arrays: Indexing

  • Indexing is different from the data arrays

Example:

» cellrowvec = {23, 'a', 1:2:9, 'hello'}

cellrowvec =

[23] 'a' [1x5 double] 'hello'

» cellrowvec(3)

ans =

1×1 cell array

{1×5 double}

» cellrowvec{3}

ans =

1 3 5 7 9

Use curly braces {}

to access values stored in cell array!

53 of 60

53

Table Arrays

  • Elements in cell arrays are columns, each assigned a header name

  • same datatype per column (can be strings, numbers or other )
  • use table function to create such arrays
  • access columns using .

Example:

» T = table(var1, … , varN)

» T = table(Age,Height,Weight,'RowNames', LastName)

» disp (T.Age)

» meanHeight = mean (T.Height)

  • use readtable/writetable functions to read from/to the file

54 of 60

54

Advanced File Operations

Example: extract data subset from a data file

% clear Workspace

clear; clear all

% load flight delay data into the array variable delay_data

delay_data = readtable('alldelays.csv');

55 of 60

55

Advanced File Operations

EUROCONTROL Performance Review Unit (PRU): ATFM arrival flight delays

56 of 60

56

Advanced File Operations

EUROCONTROL Performance Review Unit (PRU): ATFM arrival flight delays

Data covers:

Years 2016-2024 (not much data for the pandemics years 2020-2021)

All European airports

57 of 60

57

Advanced File Operations

Example: extract data subset from a data file

% clear Workspace

clear; clear all

% load flight delay data into the array variable delay_data

delay_data = readtable('all delay.csv');

% extract delay data for the particular airport of Munich

munich_data = delay_data(strcmp(delay_data.APT_ICAO, 'EDDM'), :);

% save the delay data for Munich airport in a separate data file

writetable(flight_data, 'munich.csv');

58 of 60

58

Advanced File Operations

EUROCONTROL Performance Review Unit (PRU): ATFM arrival flight delays

Query examples:

  • What is the total number of flights delayed at Munich airport in July 2019?
  • What is the total amount of delays in minutes recorded at Munich airport in 2023?
  • For how many days in May 2023 the airport has experienced delays?
  • What were the main causes of Munich airport delays in 2023?
  • What is the share of the airport delays attributed to weather at Munich airport in 2023?
  • Compare the delay records (in total number of delayed flights and minutes of delays) at two airports of your choice, etc.

59 of 60

59

Advanced File Operations

Example: analyse the delays in Munich airport

% Clean the data to leave only the rows containing information about the delays

num_lines = size(flight_data,1)

count = 0;

for i=1:(num_lines-1)

if (munich_data.DLY_APT_ARR_1{i}>0)

count = count +1;

delay_data_munich(count,:) = flight_data(i,:);

end

end

writetable(delay_data1,'munich_delays.csv')

60 of 60

THANK YOU!

60

Questions?