-
Notifications
You must be signed in to change notification settings - Fork 4
/
Code.m
148 lines (117 loc) · 2.53 KB
/
Code.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
clear all;
clc;
N=1000;
h=0.01;
v=1;
wmin=-pi*4;
wmax=pi*4;
%initial conditions
y0=1.5;
h0=0;
r=1;
Q=[1 0; 0 1];
%x = quadprog(H,f,A,b,Aeq,beq,lb,ub,x0)
%objective function
H = sparse(eye(N)*r); %identity matrix with size N with diagonal r
for i = 1:N
H = blkdiag(H, Q);
end
H = 2 * H;
f = zeros(3*N,1);
%inequality constraint
%Aineq: Matrix in linear inequality constraints Aineq*x ? bineq
%bineq: Vector in linear inequality constraints Aineq*x ? bineq
Aineq = sparse([eye(N) zeros(N,2*N);-1*eye(N) zeros(N,2*N)]);
bineq = sparse([ones(N,1)*(-wmin); ones(N,1)*wmax]);
%equality constraint
%Aeq: Matrix in linear equality constraints Aeq*x = beq
%beq: Vector in linear equality constraints Aeq*x = beq
LEFTMATRIX = zeros(2*N,N);
for i = 1:N
LEFTMATRIX(2*i,i)=-h;
end
RIGHTMATRIX = zeros(2*N,2*N);
for i = 1:2*N
if mod(i,2) == 1 %if odd
RIGHTMATRIX(i,i)=1;
if (i<2*N-1)%to prevent out of indexing
RIGHTMATRIX(i+2,i)=-1;
end
else %if even
if i<2*N-1
RIGHTMATRIX(i,i)=1;
RIGHTMATRIX(i+1,i)=-h*v;
RIGHTMATRIX(i+2,i)=-1;
elseif i<2*N
RIGHTMATRIX(i,i)=1;
RIGHTMATRIX(i+1,i)=-h*v;
else %i=2*N
RIGHTMATRIX(i,i)=1;
end
end
end
Aeq = [LEFTMATRIX RIGHTMATRIX];
beq = [y0+h*v*h0; h0; zeros(2*N-2,1)];
[x, fval] = quadprog(H,f,Aineq,bineq,Aeq,beq);
% x = [w0 w1 ... wn x1 x2 ...xn]
%construct {w}
w = x(1:N);
yk = zeros(1,1000); %initializing
hk = zeros(1,1000);
%construct {yk}
loopcounter=1;
for i=N+1:3*N
if mod(i,2)==1
yk(loopcounter)= x(i);
loopcounter = loopcounter +1;
end
end
%construct {hk}
loopcounter1=1;
for i=N+1:3*N
if mod(i,2)==0
hk(loopcounter1)= x(i);
loopcounter1 = loopcounter1 +1;
end
end
t=(0:N)*h;
%subplot(3,1,1);
%plot(t,[y0 yk]);
%title('{yk}');
%xlabel('Time (s)')
%ylabel('Position');
%subplot(3,1,2);
%plot(t, [h0, hk]);
%title('{hk}');
%xlabel('Time (s)');
%ylabel('Heading');
%subplot(3,1,3);
%plot(t(1:N), w);
%title('Turn Rate');
%xlabel('Time (s)');
%ylabel('w (rad/s)');
%%
%f) simulation with noise
y=zeros(1,N+1);
head=zeros(1,N+1);
y(1)=1.5;
head(1)=0;
for i=1:N
y(i+1)=y(i)+h*v*head(i);
head(i+1)=head(i)+h*w(i)+h*pi/25;
end
t=(0:N)*h;
%plot(t,y);
%hold on;
%plot(t,[y0 yk]);
%legend('with noise', 'without noise');
%xlabel('time (s)');
%ylabel('Position');
%title('{yk}');
plot(t,head);
hold on;
plot(t,[h0 hk]);
legend('with noise', 'without noise');
xlabel('time (s)');
ylabel('Heading');
title('{hk}');