1 of 57

Programming Basics for Logistics Algorithms: Lecture 1

Tatiana Polishchuk

Associate Professor, 

Linköping University, KTS

www.itn.liu.se/~tatpo46/

1

2 of 57

Course goals

  • To introduce some basic programming ideas common to all programming languages
  • To show you how to use Matlab
  • To give examples of some tasks logistics algorithms
  • To provide code you can reuse later in your projects
  • To make some pretty pictures

2

3 of 57

2024 Course Evaluation

Only 3 answered

Impossible to draw any conclusions. (The link to the full evaluation document)

Online coding in the lectures -> is not going to be implemented (not a hands-off tutorial, but theoretical foundation and overview)

Some changes are expected in HW evaluation and in-lab exam

3

4 of 57

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

4

5 of 57

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
  • Data management
  • Good programming practices

5

6 of 57

6

What does computer programming mean?

What is a programming language?

What is code?

What is a computer program?

Introduction to Programming

7 of 57

7

What is a computer program?

Something you use to achieve some task on a computer (or phone, tablet etc)…

Word

Write a letter, essay, lab report etc…

Excel

Analyse results, produce graphs for your report etc…

Angry Birds

Kill time when you’re sitting in boring Matlab lectures…

8 of 57

8

What is a computer program?

Image(s)

Lab results

Patient data

DATA

Do something clever…

PROGRAM

Hopefully clinically useful!

RESULT

Example: in medical imaging…

9 of 57

9

What is a computer program?

DATA

Measure volume of grey/white matter…

PROGRAM

Predict whether the patient has Alzheimer’s Disease

RESULT

MR images of the brain

Example: in medical imaging…

10 of 57

10

What is a computer program?

DATA

Measure amount dense breast tissue…

PROGRAM

Predict risk of developing breast cancer

RESULT

Mammogram acquired during routine screening + patient data

Example: in medical imaging…

11 of 57

11

What does computer programming mean?

Writing your own computer programs...

… telling the computer to do exactly what you want.

What is a programming language?

A way of translating human logic into commands a computer understands…

… like human languages, there a lots of different languages (often similar to each other), each with a specific set of rules (syntax, grammar) to obey.

What is ‘code’?

A chunk of commands in a specific programming language…

A program consists of bits of code put together in a logical way …

… by using other people’s code, you can incorporate bits of their program in your own (as long as you’re using the same language!).

12 of 57

12

Why do I need to learn how to write my own computer code?

Think of it like learning to cook…..

Now the big question….

13 of 57

13

You’re hungry and want something good to eat…..

Get mum to cook

Go to a restaurant

Get a microwave meal

x

x

x

You live alone now!

You’re student, you can’t afford it!

You’re a fussy eater!

14 of 57

14

Vs

Heating someone else’s food in the microwave

Ok if they’ve cooked exactly what you want

Cooking your own food

Can eat exactly as you like it

Vs

Using a computer program

Ok if it does exactly what you want

Writing your own computer program

Make it do exactly what you want

Research is likely to be here

15 of 57

15

How good a cook/programmer do I need to be?

Do I need to write all my programs from scratch?

No! Just like in cooking, you don’t need make everything from raw ingredients, can use pre-made pasta, sauces, wine etc…

Remember you can use other people’s code to include bits of their programs in yours …

… but you do need to know the basics to put those bits together (how to chop an onion, when to add seasoning etc.)

Vs

16 of 57

16

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!

17 of 57

Matlab

  • Stands for MATrix LABoratory
  • Interpreted language
  • Scientific programming environment
  • Very good tool for the manipulation of matrices
  • Great visualisation capabilities
  • Loads of built-in functions
  • Easy to learn and simple to use

Quiz: preliminaries

17

18 of 57

Matlab Desktop

18

Command Window

Workspace

19 of 57

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

  • Try using and
    • Select earlier expressions and edit them

19

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

20 of 57

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

20

21 of 57

Questions?

Next: Variables and Data Types

21

22 of 57

Variables and Data Types

                  • Something that can vary (not constant)

Example:

variable My_trip_duration

constant Train_trip_duration = 25 min

constant Car_trip_duration = 30 min

constant Bus_trip_duration = 5 min

If I travel by train + bus

> My_trip_duration = train_trip_duration + Bus_trip_duration + … = 30 min +…

Or

If I travel by car

> My_trip_duration = car_trip_duration = 30 min

22

What is a VARIABLE?

23 of 57

Variables and Data Types

23

Data type = class

24 of 57

Matlab Desktop

24

Variables

25 of 57

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

25

26 of 57

Variable

  • Is a location in memory in which you can temporarily store text or numbers
  • Used as an empty box
  • You can assign a name to the box, and change its contents in your program

26

27 of 57

Variables of different Types

27

Size depends on the Type

All fit together in the same memory

28 of 57

Variables and Data Types in Matlab

28

Data type = class

>> class (x)

ans = double

1 byte = 8 bits

1 2 3 4 5 6 7 8

29 of 57

29

double

default: double

Float or real numbers with a decimal place

E.g. 5.3, 6,6666, 3.14159265359

Variables and Data Types in Matlab

30 of 57

Variables and Data Types

30

Int8

uint8

Unsigned integer

0, 1, 2, 3…

Integer with sign

-1, 0, 1, 2, … 127

31 of 57

Variables and Data Types

31

char -

Characters or strings

‘x’, ‘end’, ‘Hello world!’

32 of 57

Variables and Data Types

32

logical

True = 1

False = 0

>> a = 3<4???

if (a) print “true”

33 of 57

Variables and Data Types

33

>> default: double

Casting – converting to other type

>> x = 6+3 >> whos

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

x1 1X1 4 int32

34 of 57

Variables in Matlab

  • Don’t have to declare type (default used)
  • Don’t even have to initialise
  • Just assign in command window

>> a=12; % variable a is assigned 12

34

Matlab prompt

assign operator

suppress command output

comment operator

Try the same line without the semicolon and comments

35 of 57

Variables

View variable contents by simply typing the variable name at the command prompt

>> a

a =

12

>>

>> a*2

ans =

24

35

36 of 57

Assigning Variables

  • Use ‘=‘ to assign variables

>> a = 4

>> b = 3 + 6

>> y = (4*a^2 +3*b^3) / 5

  • Can also self-assign:

>> b = b*2

  • Check the workspace

36

37 of 57

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

37

38 of 57

38

i, j:

pi: ans

Inf, NaN:

Variable Names

and some more..

39 of 57

39

  • sqrt(2)
  • log(2), log10(0.23)
  • cos(1.2), atan(-.8)
  • exp(2+4*1i)
  • round(1.4), floor(3.3), ceil(4.23)
  • angle(1i); abs(1+1i);

Built-in Functions

40 of 57

Questions?

Next: Scripts

40

41 of 57

Scripts

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

41

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

42 of 57

Scripts

  • Scripts will manipulate and store variables and matrices in the Matlab Workspace

  • They can be called from the Matlab command line by typing the (case sensitive!) filename of the script file.

>> myscript

  • Scripts can be also opened in the editor by the following

>> open myscript

42

Press Run button to run the script

43 of 57

Scripts

  • Click the ‘New script’ button (top left of main menu)
    • Opens a blank page in the editor
  • Use clear to wipe the current memory
    • Check that the workspace is now empty
  • Add several lines with commands
  • Save the document as ‘my_first_script.m’
  • Type my_first_script (note the lack of ‘.m’) at the command line

>> my_first_script

43

44 of 57

Suppressing visual output

  • Try

>> a = 10

  • This creates a variable and assigns is a value 10
  • Try

>> a = 10;

44

Do you see the difference?

45 of 57

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

45

46 of 57

The Matlab path

  • Type ‘path’ at the command line

>> path

  • This displays all the folders on your computer where Matlab will ‘look’ for functions and scripts
  • Use ‘File -> Set path’ to add new folders
  • If 2 functions/scripts have the same name, Matlab uses the first one it finds on the path
    • Avoid name clashes with existing functions
    • Avoid mixing variable and function names

46

47 of 57

Scripts

  • Scripts allow us to run sequences of commands
  • All data is stored in the main workspace, as if we typed the commands in the command window
  • We can run parts of scripts by
    • Selecting text and hitting F9
    • Using %% to create ‘cells’ (to mark beginning of the blocks)

47

Even when ‘hacking around’ use scripts, date tagged (e.g. work2013_02_11) to run commands

    • That way you have a record of your work
    • Think of them as your Matlab lab book

48 of 57

Organising your scripts

  • Use scripts to generate results/output for specific tasks
    • Assignments in your maths course
    • Experiments in your project
    • Give them a sensible name, and add comments at the start describing what they do
  • Remember, you can always rearrange the file structure
    • As long as you remember to add any new folders to the path

48

49 of 57

Questions?

Next: Input/Output

  • Debugging

49

50 of 57

50

Hello world! This is my first Matlab script!

Input/Output

>> disp (‘Hello world!’)

Displays the string in parentheses

Remember to put text into ‘ ’

Exercise:

51 of 57

51

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)

52 of 57

52

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)

What is your name> Olof

Written by

Olof

Use when you expect a string

53 of 57

53

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

54 of 57

54

Input/Output

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

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

The value is 64.000, for sure!

6 positions, 3 after decimal point

55 of 57

55

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

56 of 57

Debugging

Set breakpoints to pause the execution of code

K>>

K>> a

a =

2

K>> return

To exit debug mode

Debug menu

Click mouse on the left of the line of code to create a breakpoint

57 of 57

Questions?

Thank you!

57