1 of 59

Programming Basics for Logistics Algorithms: Lecture 2

Tatiana Polishchuk

Associate Professor, 

Linköping University, KTS

www.itn.liu.se/~tatpo46/

1

2 of 59

Course Overview�Lecture 1

  • 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

2

3 of 59

Course Overview�Lecture 2

  • 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

3

4 of 59

Flashback: Lecture 1

4

5 of 59

5

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!

6 of 59

6

What is a computer program?

Image(s)

Lab results

Patient data

DATA

Do something clever…

PROGRAM

Hopefully clinically useful!

RESULT

Example: in medical imaging…

7 of 59

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

7

8 of 59

Matlab Desktop

8

Variables

Command Window

9 of 59

Scripts

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

9

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

Press Run button to run the script

10 of 59

10

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

11 of 59

11

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

12 of 59

12

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:

'' Single quotation mark %% Percent character

\t Horizontal tab \\ Backslash

new line

13 of 59

Questions?

Next: Algorithms

13

14 of 59

Algorithms

What is algorithm? (watch video 5 min)

  • a set of rules to be followed in calculations or other problem-solving operations, especially by a computer

or simply:

  • a sequence of steps needed to solve a problem

Pseudocode

- a simplified programming language, used in program design

14

15 of 59

Example: Area of a Circle

Algorithm (pseudocode):

  • Input radius r
  • Calculate the area A
  • Display the output

15

Matlab code:

r = input ('Radius of the circle r = ');

A = pi*r^2;

disp ('Area of the circle A=')

disp (A)

16 of 59

Algorithm

16

Input

Output

Calculations

A typical sequential structure. Can be more complicated inside…

17 of 59

Algorithm

17

18 of 59

Questions?

Next: Flow Control

18

19 of 59

if/else/elseif

19

  • 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

20 of 59

Example: Area of a Circle

20

ATTN:

r>=0!

21 of 59

Relational Operators

21

  • 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

Logical ‘or’ = only one is true

22 of 59

Conditional Statement

22

any non-zero value!

>> ANS: True

23 of 59

Conditional Statement

23

any non-zero value!

>> ANS: True

>> ANS: False

24 of 59

Conditional Statement

24

any non-zero value!

>> ANS: True

>> ANS: False

>> ANS: ALWAYS YES!!

WHY??

25 of 59

Conditional Statement

25

any non-zero value!

>> ANS: True

>> ANS: False

26 of 59

Nested If-else

26

Example: continuous mathematical function y(x):

27 of 59

Nested If-else

27

Example: continuous mathematical function y(x):

NOT efficient:

Better way:

28 of 59

Elseif

28

Example: continuous mathematical function y(x):

One more way: even more efficient

Note: only one ‘ end ‘ needed

ELSEIF

if cond1

commands1 elseif cond2

commands2 else

commands3 end

29 of 59

Switch

29

SWITCH

switch switch_expression

case case_expression 1

commands 1

case case_expression 2

commands 2

case case_expression 3

commands 3

... can be many of cases

otherwise (optional)

commands

end

- expression: scalar or string

- case_expressions are values

- one case at a time

when no cases match

30 of 59

Switch

30

Example: assign a letter grade corresponding to the integer number of points

Another way:

Using IF:

31 of 59

Menu

31

Example of Switch function usage

32 of 59

Questions?

Next: Loops

32

33 of 59

for

33

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

34 of 59

for

34

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

35 of 59

for

35

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

36 of 59

Nested for loops

37 of 59

Nested for loops

37

i = 1

j = 1

j = 2

i = 2

j = 1 %repeat

j = 2

i = 3

j = 1 %repeat

j = 2

inner loop

outer loop

38 of 59

while

38

  • 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?!

39 of 59

39

>>

i =

4

i =

16

i =

256

while

Step by step:

before the loop: 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

40 of 59

Next: Arrays

40

Questions?

41 of 59

Preliminaries: Vectors and Matrices

Quiz: Arrays and Matrices

https://tinyurl.com/tnsl24-vector

41

42 of 59

42

… I want to do something fun with images!

Those labs are dull…

43 of 59

What does an image look like to a computer?

43

A computer ‘sees’ an image as an array of numbers…

…. the value of each pixel represents its intensity (or colour)

We call each number a pixel (or in 3D a voxel)…

44 of 59

44

… I need to understand how to use arrays

So to learn how to do stuff with images…

45 of 59

Arrays

  • Matlab was originally designed to allow efficient and intuitive processing of vectors and matrices
  • Understanding how to use arrays is the key to successfully working with Matlab
  • Later we’ll see more on how images in Matlab are plotted using the arrays of numbers

45

46 of 59

1D Arrays: vectors

46

  • row = [ 1 2 3.2 4 6 5.4 ];
  • row = [ 1, 2, 4, 7, 4.3, 1.1 ];

47 of 59

1D Arrays: vectors

47

  • col = [ 1; 2; 3.2; 4; 6; 5.4 ];

48 of 59

1D Arrays: vectors

48

49 of 59

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

49

50 of 59

Automatic Initialization

50

)

(1,69

  • Initialize a vector of ones, zeros, or random numbers

» o=ones(1,10)

    • Row vector with 10 elements, all 1

» z=zeros(23,1)

    • Column vector with 23 elements, all 0

» r=rand(1,45)

    • Row vector with 45 elements (uniform (0,1))

» n=nan

    • Row vector of NaNs (representing uninitialized variables)

51 of 59

1D Arrays: vectors

51

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

52 of 59

1D Arrays: vectors

52

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

answer:

>> c = 9:-2:1

53 of 59

1D Arrays: vectors

53

linspace (x, y, n) function: creates a vector with n values in the inclusive range from x to y

>> v = linspace(3, 15, 5)

v = 3 6 9 12 15

logspace (x, y, n) function: creates a logarithmically spaced vector with n values in the inclusive range from 10^x to 10^y

>> logv = logspace(1, 5, 5)

logv =10 100 1000 10000 10000

Create vector using variables (Concatenation)

>> a = [1 10 100];

>> b = [2 3 4 5];

>> c = [a b]

c = 1 10 100 2 3 4 5

54 of 59

1D Arrays: Indexing and

accessing elements

54

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

55 of 59

1D Arrays: Changing values

55

Changing vector elements values

>> myvector=[1 3 5]

>> myvector (1) = 100;

>> myvector

myvector = 100 3 5

Adding new elements to the vector

>> myvector(4) = 11

>> myvector

myvector = 100 3 5 11

>> size (myvector)

ans = 1 4

new value

new element

Adding new elements to the vector

>> myvector(6) = 20

>> myvector

myvector = 100 3 5 11 0 20

>> size (myvector)

ans = 1 6

fills the gap

56 of 59

1D Arrays: Transpose

56

No way to use : operator directly

But can use transpose

>> myvector=1:2:5;

>> myvector

myvector = 1 3 5 7

>> myvector

myvector =

1

3

5

7

Creating column vector

>> myvector=[1; 3; 5; 7];

>> myvector

myvector=

1

3

5

7

transpose

57 of 59

1D Arrays: Concatenation

57

Add elements to the empty vector

>> myvector=[];

>> myvector = [myvector 4]

myvector=

4� >> myvector = [myvector 2]

myvector =

4 2

Can be continued as many times as needed!

58 of 59

1D Arrays: Concatenation

58

Similarly we can create vectors of chars

>> myvector=['A', 'O', 'K', 'J'];

>> myvector = [myvector, 'B']

myvector=['A', 'O', 'K', 'J','B' ]

59 of 59

Next time: 2d Arrays=Matrices

59

Thank you!