Attachment 'Example Scripts GLM 27Feb13.m'
Download 1 %% Decomposition of vectors
2
3 1*[1 0 0] + 2*[0 1 0] + 3*[0 0 1]
4
5 1*[1 1 1] + 1*[0 1 0] + 2*[0 0 1]
6
7 -1*[1 -1 0] + -1*[0 1 -1] + 2*[1 1 1]
8
9 %% matrix inversion
10 % define a matrix
11 x = [1 1; 1 -1]
12
13 % multiply data with inverse matrix
14 inv(x)*[1 1]'
15 inv(x)
16
17 %% trivial example
18 x = [2 0; 0 3];
19 inv(x)
20
21 %% parameter estimation - forward model
22 x = 0:0.1:8*pi; % abscissa values
23
24 figure;
25 y1 = x'; % straight line (note transpose)
26 plot(x, y1);
27
28 figure;
29 y2 = sin(x)'; % sine curve
30 plot(x, y2);
31
32 figure;
33 y3 = exp(-x/2)'; % exponential function
34 plot(x, y3);
35
36 % Generate data with some noise
37 figure;
38 y = y1/5 + y2 + 5*y3 + 0.5*randn(length(y1),1);
39 plot(x, y);
40
41 whos
42 %% Estimating the parameters using minimum least-squares (MNLS)
43 % creating the design matrix
44 M = [y1 y2 y3];
45 whos
46
47 % check correlation among basis functions
48 corr(M)
49
50 % (pseudo)inverting the design matrix
51 Minv = pinv(M);
52 whos
53
54 % getting the solution
55 b = Minv*y
56
57 % checking how solution predicts the data
58 figure;
59 ypred = b(1)*y1 + b(2)*y2 + b(3)*y3;
60 plot(x, ypred)
61
62 % compare with "ground truth"
63 hold on; % don't overwrite figure
64 yreal = y1/5 + y2 + 5*y3;
65 plot(x, yreal, 'r');
66
67 % plot the difference between measured and predicted data
68 figure;
69 ydiff = y - ypred;
70 plot(x, ydiff);
71
72 % variance of difference
73 var(ydiff)
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.