Modeling and Simulating Social Systems with MATLAB Lecture 2 - - PowerPoint PPT Presentation

modeling and simulating social systems with matlab
SMART_READER_LITE
LIVE PREVIEW

Modeling and Simulating Social Systems with MATLAB Lecture 2 - - PowerPoint PPT Presentation

Modeling and Simulating Social Systems with MATLAB Lecture 2 Statistics and Plotting in MATLAB Stefano Balietti, Olivia Wolley, Dirk Helbing Computational Social Science ETH Zrich Exercise 1 Compute: 100 18 + 107 i a)


slide-1
SLIDE 1

ETH Zürich

Modeling and Simulating Social Systems with MATLAB

Lecture 2 – Statistics and Plotting in MATLAB

Computational Social Science

Stefano Balietti, Olivia Wolley, Dirk Helbing

slide-2
SLIDE 2

Modeling and Simulating Social Systems with MATLAB 2 2

Exercise 1

  • Compute:

a) b) c)

18+ 107 5×25

i=0 100

i

i=5 10

(i2−i )

slide-3
SLIDE 3

Modeling and Simulating Social Systems with MATLAB 3 3

Exercise 1 – solution

  • Compute:

a)

18+ 107 5×25

>> (18+107)/(5*25) ans = 1

slide-4
SLIDE 4

Modeling and Simulating Social Systems with MATLAB 4 4

Exercise 1 – solution

  • Compute:

b)

i=0 100

i

>> s=sum(1:100)

  • r

>> s=sum(1:1:100)

  • r

>> s=sum(linspace(1,100))

  • r

>> s=sum(linspace(1,100,100)) s = 5050

default value default value

slide-5
SLIDE 5

Modeling and Simulating Social Systems with MATLAB 5 5

Exercise 1 – solution

  • Compute:

c) ∑

i=5 10

(i2−i)

>> s=0; >> for i=5:10 >> s=s+i^2-i; >> end >> s s = 310

slide-6
SLIDE 6

Modeling and Simulating Social Systems with MATLAB 6 6

Exercise 2

  • Solve for x:

2x1−3x2−x3+4x4=1 2x1+ 3x 2−3x3+2x4=2 2x1−x2−x3−x 4=3 2x1−x2+2x3+ 5x4=4

slide-7
SLIDE 7

Modeling and Simulating Social Systems with MATLAB 7 7

Exercise 2 – solution

>> A=[2 -3 -1 4; 2 3 -3 2; 2 -1 -1 -1; 2 -1 2 5]; >> b=[1; 2; 3; 4]; >> x=A\b x = 1.9755 0.3627 0.8431

  • 0.2549

>> A*x ans = 1.0000 2.0000 3.0000 4.0000

2x1−3x2−x3+4x4=1 2x1+ 3x 2−3x3+2x4=2 2x1−x2−x3−x 4=3 2x1−x2+2x3+ 5x4=4

Ax=b

slide-8
SLIDE 8

Modeling and Simulating Social Systems with MATLAB 8 8

Exercise 3

  • Fibonacci sequence: Write a function which

computes the Fibonacci sequence until a given number n and return the result in a vector.

  • The Fibonacci sequence F(n) is given by :
slide-9
SLIDE 9

Modeling and Simulating Social Systems with MATLAB 9 9

Exercise 3 – iterative solution

fibonacci.m: function [v] = Fibonacci(n) v(1) = 0; if ( n>=1 ) v(2) = 1; end for i=3:n+1 v(i) = v(i-1) + v(i-2); end end >> Fibonacci(7) ans = 0 1 1 2 3 5 8 13

slide-10
SLIDE 10

Modeling and Simulating Social Systems with MATLAB 10 10

Exercise 3 – recursive solution

fibo_rec.m: function f = fibo_rec(n) if n == 0 f(1) = 0; elseif n == 1 f(2) = 1; elseif n > 1 f = fibo_rec(n - 1); f(n + 1) = f(n) + f(n - 1); end end >> fibo_rec(7) ans = 0 1 1 2 3 5 8 13

slide-11
SLIDE 11

Modeling and Simulating Social Systems with MATLAB 11 11

Plotting and Statistics in Matlab

slide-12
SLIDE 12

Modeling and Simulating Social Systems with MATLAB 12 12

Statistics functions

  • Statistics in MATLAB can be performed with the

following commands:

Mean value: mean(x) Median value: median(x) Min/max values: min(x), max(x) Standard deviation: std(x) Variance: var(x) Covariance: cov(x) Correlation coefficient: corrcoef(x) Vector-based Matrix-based

slide-13
SLIDE 13

Modeling and Simulating Social Systems with MATLAB 13 13

Statistics functions: focus on covariance

  • Covariance and correlation coefficient are linked

by a precise mathematical function

  • They express the same type of information, but

the correlation coefficient is often more useful. Why?

ρ= s xy s xs y

slide-14
SLIDE 14

Modeling and Simulating Social Systems with MATLAB 14 14

Where can I get help?

>>help functionname

  • >>doc functionname
  • >>helpwin
  • Click on “More Help” from contextual pane after
  • pening first parenthesis, e.g.: plot(…
  • Click on the Fx symbol before command prompt.
  • Online! e.g. MathWorks
slide-15
SLIDE 15

Modeling and Simulating Social Systems with MATLAB 15 15

2D Plotting functions

  • 2D plotting of curves (y vs x) in MATLAB

Linear scale: plot(x, y) Double-logarithmic scale: loglog(x, y) Semi-logarithmic scale: semilogx(x, y) semilogy(x, y) Plot histogram of x: hist(x)

slide-16
SLIDE 16

Modeling and Simulating Social Systems with MATLAB 16 16

Logarithmic Scale

  • It uses the logarithm of a physical quantity instead of the

quantity itself.

  • E.g., increment on the axis are powers of 10 (1,10,100,

1000,…) instead of 1, 2, 3, 4.

  • Examples:
slide-17
SLIDE 17

Modeling and Simulating Social Systems with MATLAB 17 17

Logarithmic Scale

  • It uses the logarithm of a physical quantity instead of the

quantity itself.

  • E.g., increment on the axis are powers of 10 (1,10,100,

1000,…) instead of 1, 2, 3, 4.

  • Examples:

Same distance between 1-2-3 and 10-20-30

slide-18
SLIDE 18

Modeling and Simulating Social Systems with MATLAB 18 18

Logarithmic Rescaling: example

?

slide-19
SLIDE 19

Modeling and Simulating Social Systems with MATLAB 19 19

Logarithmic Rescaling: example

slide-20
SLIDE 20

Modeling and Simulating Social Systems with MATLAB 20 20

Logarithmic Scale: examples

  • Decibel
  • Richter scale
  • Entropy in thermodynamics
  • Information in information theory.
  • PH for acidity and alkalinity;
  • Stellar magnitude scale for brightness of stars
  • bit [log 2] and the byte 8[log 2]
slide-21
SLIDE 21

Modeling and Simulating Social Systems with MATLAB 21 21

Logarithmic Scale: why and when to use it

  • If the data cover a large range of values the logarithm

reduces this to a more manageable range.

  • Some of our senses operate in a logarithmic fashion

(Weber–Fechner law)

  • Some types of equations get simplified:
  • Exponential: Y = eaX -> semilog scale -> Y = -aX
  • Power Law: Y = Xb -> log-log scale -> logY = b logX
slide-22
SLIDE 22

Modeling and Simulating Social Systems with MATLAB 22 22

Logarithmic Scale

slide-23
SLIDE 23

Modeling and Simulating Social Systems with MATLAB 23 23

Back to plotting… details of plot

  • An additional parameter can be provided to

plot() to define how the curve will look like: plot(x, y, ‘key’) Where key is a string which can contain: Color codes: ‘r’, ‘g’, ‘b’, ‘k’, ‘y’, … Line codes: ‘-’, ‘--’, ‘.-’ (solid, dashed, etc.) Marker codes: ‘*’, ‘.’, ‘s’, ’x’ Examples: plot(x, y, ‘r--’) plot(x, y, ‘g*’) * * * *

slide-24
SLIDE 24

Modeling and Simulating Social Systems with MATLAB 24 24

Plotting tips

  • To make the plots look nicer, the following

commands can be used: Set label on x axis: xlabel(‘text’) Set label on y axis: ylabel(‘text’) Set title: title(‘text’)

slide-25
SLIDE 25

Modeling and Simulating Social Systems with MATLAB 25 25

  • Setting axes limits
  • xlim([xmin xmax])
  • ylim([ymin ymax])

Plotting tips

slide-26
SLIDE 26

Modeling and Simulating Social Systems with MATLAB 26 26

  • Two additional useful commands:
  • hold on|off
  • grid on|off

>> x=[-5:0.1:5]; >> y1=exp(-x.^2); >> y2=2*exp(-x.^2); >> y3=exp(-(x.^2)/3);

Plotting tips

slide-27
SLIDE 27

Modeling and Simulating Social Systems with MATLAB 27 27

Plotting tips

>> plot(x,y1); >> hold on >> plot(x,y2,’r’); >> plot(x,y3,’g’);

slide-28
SLIDE 28

Modeling and Simulating Social Systems with MATLAB 28 28

Plotting tips

>> plot(x,y1); >> hold on >> plot(x,y2,’r’); >> plot(x,y3,’g’); >> grid on

slide-29
SLIDE 29

Modeling and Simulating Social Systems with MATLAB 29 29

Subplot()

  • subplot(m,n,p) breaks the figure window into an m-

by-n matrix and selects the pth axes object for the current plot.

  • The axes are counted along the top row of the figure

window, then the second row, etc.

slide-30
SLIDE 30

Modeling and Simulating Social Systems with MATLAB 30 30

Subplot() by the way…

We have already seen an example

  • f a chart created using subplot

last lecture. Can you reproduce it?

slide-31
SLIDE 31

Modeling and Simulating Social Systems with MATLAB 31 31

Handles, figure(), set() and get()

  • h = figure(...)adds a new figure window to the
  • screen. It also returns the handle to it, so it can be further

processed.

  • Figure handle: gcf

Axes handle: gca

  • get(handle,'PropertyName')
  • set(handle,'PropertyName',PropertyValue,...)

e.g. set(gcf, 'Position', [100 100 150 150]) [left bottom width height];

slide-32
SLIDE 32

Modeling and Simulating Social Systems with MATLAB 32 32

Saving and printing figures

  • saveas(handle,’myimage.fig’);
  • saveas(handle,’myimage.jpg’);
  • export_fig from MathWorks File Exchange

http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig

export_fig('/plots/myimage.pdf', '-pdf', '-nocrop')

slide-33
SLIDE 33

Modeling and Simulating Social Systems with MATLAB 33 33

Exercises: working with datasets

  • Two datasets for statistical plotting can be found
  • n the course web page (with NETHZ login)
  • http://www.coss.ethz.ch/education/matlab.html

you will find the files: countries.m cities.m

slide-34
SLIDE 34

Modeling and Simulating Social Systems with MATLAB 34 34

Exercises: Datasets

  • Download the files countries.m and

cities.m and save them in the working directory of MATLAB.

slide-35
SLIDE 35

Modeling and Simulating Social Systems with MATLAB 35 35

Exercises: Datasets – countries

  • This dataset countries.m contains a matrix A

with the following specification:

  • Rows: Different countries
  • Column 1: Population
  • Column 2: Annual growth (%)
  • Column 3: Percentage of youth
  • Column 4: Life expectancy (years)
  • Column 5: Mortality
slide-36
SLIDE 36

Modeling and Simulating Social Systems with MATLAB 36 36

Exercises: Datasets – countries

  • Most often, we want to access complete

columns in the matrix. This can be done by A(:, index) For example if you are interested in the life- expectancy column, it is recommended to do: >> life = x(:,4); and then the vector life can be used to access the vector containing all life expectancies.

slide-37
SLIDE 37

Modeling and Simulating Social Systems with MATLAB 37 37

Exercises: Datasets – countries

  • The sort() function can be used to sort all

items of a vector in inclining order. >> life = A(:, 4); >> plot(life)

slide-38
SLIDE 38

Modeling and Simulating Social Systems with MATLAB 38 38

Exercises: Datasets – countries

  • The sort() function can be used to sort all

items of a vector in inclining order. >> life = A(:, 4); >> lifeS = sort(life); >> plot(lifeS)

slide-39
SLIDE 39

Modeling and Simulating Social Systems with MATLAB 39 39

Exercises: Datasets – countries

  • The histogram hist() is useful for getting the

distribution of the values of a vector. >> life = A(:, 4); >> hist(life)

slide-40
SLIDE 40

Modeling and Simulating Social Systems with MATLAB 40 40

Exercises: Datasets – countries

  • Alternatively, a second parameter specifies the

number of bars: >> life = A(:, 4); >> hist(life, 30)

slide-41
SLIDE 41

Modeling and Simulating Social Systems with MATLAB 41 41

Exercise 1

  • Statistics: Generate a vector of N random

numbers with randn(N,1) Calculate the mean and standard deviation. Do the mean and standard deviation converge to certain values, for an increasing N? Optional: Display the histogram and compare the

  • utput of the following two commands
  • hist(randn(N,1))
  • hist(rand(N,1))
slide-42
SLIDE 42

Modeling and Simulating Social Systems with MATLAB 42 42

Exercise 2

  • Demographics: From the countries.m dataset,

find out why there is such a large difference between the mean and the median population of all countries. Hint: Use hist(x, n) Also sort() can be useful.

  • Plus: play with subplot()
slide-43
SLIDE 43

Modeling and Simulating Social Systems with MATLAB 43 43

Exercise 3

  • Demographics: From the countries.m dataset,

see which columns have strongest correlation. Can you explain why these columns have stronger correlations? Hint: Use corrcoef() to find the correlation between columns. Use imagesc()to get an immediate visualization of the correlations.

slide-44
SLIDE 44

Modeling and Simulating Social Systems with MATLAB 44 44

Exercise 4 – optional

  • Zipf’s law: Zipf’s law says that the rank, x, of

cities (1: largest, 2: 2nd largest, 3: 3rd largest, ...) and the size, y, of cities (population) has a power-law relation: y ~ xb

  • Test if Zipf’s law holds for the cases in the

cities.m file. Try to estimate b. Hint: Use log() and plot() (or loglog())

  • Plus: use the fitting tool cftool() to get b
slide-45
SLIDE 45

Modeling and Simulating Social Systems with MATLAB 45 45

References

  • Additional material on plotting on the home page
  • f the course

http://www.coss.ethz.ch/education/matlab.html

  • "Log or Linear? Distinct Intuitions of the Number

Scale in Western and Amazonian Indigene Cultures”, Science 320 (5880): 1217

  • Fechner law