Programming Basics for Logistics Algorithms: Lecture 5
1
Course Overview
2
Course Overview
3
Flashback: Lecture 4
4
Questions?
Plotting
5
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])
Plot Options
6
Saving Figures
7
.fig preserves all information
.bmp uncompressed image
.eps high-quality scaleable format
.pdf compressed image
3D Line Plots
8
» t=0:0.001:4*pi;
» x = sin(t);
» y = cos(t);
» plot3(x,y,t,'k','LineWidth',2);
» xlim, ylim, zlim
Specialized Plotting Functions
9
» polar (0:0.01:2*pi, cos ((0:0.01:2*pi)*2));
» bar (1:10, rand(1,10));
» [X,Y] = meshgrid (1:10,1:10);
» quiver(X,Y, rand(10),rand(10));
» stairs(1:10, rand(1,10));
» fill ([0 1 0.5], [0 0 1], ‘r’);
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);
10
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 , 'EdgeLabel', G.Edges.Weight);
11
Next: Data Management
12
Questions?
13
File Operations
14
Read from the file
load filename
15
File Operations
save filename matrixname -ascii
16
File Operations
save filename matrixname -ascii -append
17
File Operations
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
18
Advanced File Operations
.txt, .dat, or .csv for delimited text files
.xls, .xlsb, .xlsm, .xlsx, .xltm, .xltx, or .ods for spreadsheet files
19
Advanced File Operations
20
Cell Arrays
Example:
» cellrowvec = {23, 'a', 1:2:9, 'hello'}
cellrowvec =
[23] 'a' [1x5 double] 'hello'
21
Cell Arrays: Indexing
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!
22
Table Arrays
Example:
» T = table(Age,Height,Weight,'RowNames', LastName)
» disp (T.Age)
» meanHeight = mean (T.Height)
Next: Good Programming Practices
23
Questions?
find
24
» x = rand(1,100);
» inds = find (x>0.4 & x<0.6);
inds is a vector which contains the indices at which x has values between 0.4 and 0.6. This is what happens:
x>0.4 returns a vector with 1 where true and 0 where false x<0.6 returns a similar vector
& combines the two vectors using logical and operator find returns the indices of the 1's
Example: Avoiding Loops
25
length(x) | Loop time | Find time |
100 | 0.01 | 0 |
10,000 | 0.1 | 0 |
100,000 | 0.22 | 0 |
1,000,000 | 1.5 | 0.04 |
Using a loop and if/else
count=0;
for n=1:length(x) if x(n)>0
count=count+1; end
end
Being more clever
count=length(find(x>0));
Logical vectors
26
» vect = [5 9 3 4 11];
» is_greater5 = vect>5;
» sum (is_greater5)
is_greater5 =
0 1 0 0 1
ans=
2
» vect = [5 9 3 4 11];
» is_greater5 = 0;
» for i = 1:5
» if vect(i)>5
» is_greater5 = is_greater5 + 1;
» end
» end
Logical vectors
27
» a = logical ([1 0 1 0 1])
» b = int8(a)
a =
1×3 logical array
1 0 1 0 1
b =
1×3 int8 row vector
1 0 1 0 1
Use true-false instead or logical 0s to avoid confusion:
a = true false true false true
Logical vectors
28
» a = false (2)
a =
0 0
0 0
» b = true (1,5)
b =
1 1 1 1 1
» any ([1 0 1 0 1]) » all ([1 0 1 0 1])
ans = ans =
1 0
Vectorization
29
v = randi([0 100],1,10);
for i=1:10
v(i) = v(i) + 50;
end
disp(v)
v = randi([0 100],1,10);
v = v + 50;
disp(v);
Vectorization
30
Sum up all elements of matrix A:
M = [1 , 2 , 1; 4 , 5, 2; 1, 3, 2];
sum_of_elements = 0;
number_of_rows = size (M , 1) ;
number_of_columns = size (M , 2) ;
% for each row
for row = 1: number_of_rows
% for each column
for column = 1: number_of_columns
sum_of_elements = sum_of_elements + M( row , column ) ;
end
end
disp ( sum_of_elements );
M = [1 , 2 , 1; 4 , 5, 2; 1, 3, 2];
sum_of_elements = sum(sum(M));
disp ( sum_of_elements );
Performance Measures
31
» tic % start timer
» My_code1;
» a= toc; % time 1
» My_code2;
» b = toc; % time 2
Performance Measures
32
Sparse matrices occupy a lot of memory, leading to inefficient codes
Function sparse converts a full matrix into sparse form by squeezing out any zero elements. If a matrix contains many zeros, converting the matrix to sparse storage saves memory.
» A = zeros(10000); A(1,3) = 10; A(21,5) = pi;
» B = sparse(A);
» tic; A*A; toc % very slow
Elapsed time is 19.949076 seconds
» tic; B*B; toc % faster!
Elapsed time is 0.07464 seconds
Performance Measures
33
» profile on
» profile viewer
Next: Mini-Project
34
Questions?
35
HW5: Mini-project on Data Analysis
1. Download flight data for from the dataset alldelays.csv to access flight delays information provided by EUROCONTROL
2. Choose a research question from the list and clearly state it, add your group number in front of the corresponding questions
3. Extract the data you need for the corresponding airports/data periods from the dataset
4. Code the calculations to answer your research question
5. Illustrate the results using 2 different types of plots in Matlab
6. Send HW5 report to the examiner (Tatiana Polishchuk) in one email, containing:
36
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
37
Mini-project
EUROCONTROL Performance Review Unit (PRU): ATFM arrival flight delays
38
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');
39
Advanced File Operations
Example: extract data subset corresponding for Munich airport
% extract delay data for the particular airport of Munich
flight_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');
40
Advanced File Operations
EUROCONTROL Performance Review Unit (PRU): ATFM arrival flight delays
Query examples:
41
Advanced File Operations
Example: analyse the delays in Munich airport: code
% 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 (flight_data.DLY_APT_ARR_1{i}>0)
count = count +1;
delay_data_munich(count,:) = flight_data(i,:);
end
end
writetable(delay_data_munich,'munich_delays.csv')
% now delay_data_clean contains only non-zero rows with delay information
% make calculations for the delays attributed to weather in Munich airport
42
Advanced File Operations
Example (cont.): analyse the delays in Munich airport code
% Calculate delays (in number of flights) Munich airport for all years
sum_delays = sum(delay_data_munich.FLT_APT_ARR_1)
% Calculate delays (in minutes) attributed to weather in Munich airport for all years
sum_weather_delays = sum(delay_data_munich.DLY_APT_ARR_W_1)
! Note: the data cells corresponding to minutes of delays is stored in “string” format in the delay datatable. This type is not appropriate for operation of summation!
There are 2 ways to resolve:
-use casting operation per cell in a loop applying str2double (it does not work for the whole column),
-or to make your life easy, open the datafile 'munich_delays.csv' (see previous slide) in Excel and format the corresponding column/cells to Number.
43
Plotting Figures
Example (cont.): analyse the delays in Munich airport code
%% Create a bar plot
figure;
bar([sum_delays, sum_weather_delays], 'FaceColor', [0.5 0.7 1]);
xticklabels({'Total Delays', 'Weather Delays'});
ylabel('Delay Minutes');
title('Munich Airport Delays');
grid on;
% Save figure
saveas(gcf, 'munich_delays_bar.png');
44
HW5: Mini-project on Data Analysis
45
HW5: Mini-project on Data Analysis
*Tips: There are many plotting functions available in Matlab. Try different types, not only the ones I’ve showed in the example.
Very useful type of plotting statistics is boxplot (see an example below, but note that it does not correspond to the delay dataset).
Boxplot: code
Next: Mini-Project
46
47
HW5: Mini-project on Data Analysis
1. Download flight data for from the dataset alldelays.csv to access flight delays information provided by EUROCONTROL
2. Choose a research question from the list and clearly state it
3. Extract the data you need for the corresponding airports/data periods from the dataset
4. Code the calculations to answer your research question
5. Illustrate the results using 2 different types of plots in Matlab
6. Send HW5 report to the examiner (Tatiana Polishchuk) in one email, containing:
48
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
49
Mini-project
EUROCONTROL Performance Review Unit (PRU): ATFM arrival flight delays
50
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');
51
Advanced File Operations
Example: extract data subset corresponding for Munich airport
% extract delay data for the particular airport of Munich
flight_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');
52
Advanced File Operations
EUROCONTROL Performance Review Unit (PRU): ATFM arrival flight delays
Query examples: full list
53
Advanced File Operations
Example: analyse the delays in Munich airport: code
% 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 (flight_data.DLY_APT_ARR_1{i}>0)
count = count +1;
delay_data_clean(count,:) = flight_data(i,:);
end
end
writetable(delay_data_clean,'munich_delays.csv')
% now delay_data_clean contains only non-zero rows with delay information
% make calculations for the delays attributed to weather in Munich airport
54
Advanced File Operations
Example (cont.): analyse the delays in Munich airport code
% Calculate delays (in number of flights) Munich airport for all years
sum_delays = sum(delay_data_clean.FLT_ARR_1)
% Calculate delays (in minutes) attributed to weather in Munich airport for all years
delay_data_clean_double = readtable('munich_clean.csv');
sum_weather_delays = sum(delay_data_clean_double.DLY_APT_ARR_W_1)
! Note: the data cells corresponding to minutes of delays is stored in “string” format in the delay datatable. This type is not appropriate for operation of summation!
There are 2 ways to resolve:
-use casting operation per cell in a loop (it does not work for the whole column),
-or to make your life easy, open the datafile 'munich_delays.csv' (see previous slide) in Excel and format the corresponding column/cells to Number.
55
HW5: Mini-project on Data Analysis
56
HW5: Mini-project on Data Analysis
*Tips: There are many plotting functions available in Matlab. Try different types, not only the ones I’ve showed in the example.
Very useful type of plotting statistics is boxplot (see an example below, but note that it does not correspond to the delay dataset).
Boxplot: code
THANK YOU!
57
Questions?