numerical analysis 0923

写在前面:本周练习题组织得十分巧妙,最终实现的动态效果也十分直观明了。
question 1: Plot $f(x)=sin(x)+cos(x)$, for $x$ between $[-2,2]$ using symbolic expression

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%matlab code:
%declare the symbolic expression
syms x;

%define the objective function f
f=sin(x)+cos(x);

%set the initial series of x
x_value=-2:0.1:2;

%get the function value of f
f_value=double(subs(f,x,x_value));

%plot the figure of f
plot(x_value,f_value);

question 2: Conduct second-order approximation for $f(x)=sin(x)+cos(x)$ at point $x=0$, using symbolic expression

1
2
3
4
5
6
7
8
9
10
11
12
13
%matlab code:
%to approximate the objective function, we must know its derivatives at certain points. we have set the symbolic x in E1, so just use it.
%first order devatives
J=jacobian(f,x);

%second order devatives
H=hessian(f,x);

%initial guess of x
x_0=0;

%get the equation of approximation
SOA=subs(f,x,x_0)+subs(J,x,x_0)*(x-x_0)+0.5*subs(H,x,x_0)*(x-x_0)^2;

question 3: Plot $f(x)=sin(x)+cos(x)$ and its second_order approximation in a single graph

1
2
3
4
5
6
7
8
9
10
11
12
%we have got f_value in E1, and the format of SOA in E2, just calculate SOA and plot them.
%get the function value of SOA
SOA_value=double(subs(SOA,x,x_value));

%plot them together
figure
plot(x_value,f_value,'-b',x_value,SOA_value,'--r','LineWidth',2);
xlabel('x');
ylabel('f(x)');
title('E3');
ylim([-3 3])
grid on

question 4: Apply Newton-Raphson method to find a local maximum for $f(x)=sin(x)+cos(x)$

1
2
3
4
5
6
7
8
9
10
11
12
%matlab code:
%define the series to store the sequence of updated maximizers
xk=zeros(100,1);
xk(1)=0;

%set the for loop to update 100 maximizers
for i=1:100
%update xk using Newton-Raphson method
x_next=xk(i)-subs(H,x,xk(i))^(-1)*subs(J,x,xk(i));
xk(i+1)=double(x_next);

end

question 5: Plot the whole iteration process with initial guess $x=0$, untill finding the local maximum for $f$.

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
%we now know how to get SOA at certain point in E2, and have already got the series of maximizers, at which we should conduct the SOA. so we just go through the xk(i) and draw the picture.
%generate an empty set
frames=[];

%set the for loop
for i =1:10

%get SOA at this point
SOA=subs(f,x,xk(i))+subs(J,x,xk(i))*(x-xk(i))+0.5*subs(H,x,xk(i))*(x-xk(i))^2;

%get the function value of SOA
SOA_value=double(subs(SOA,x,x_value));

%plot them together
figure
plot(x_value,f_value,'-b',x_value,SOA_value,'--r','LineWidth',2);
xlabel('x'); ylabel('f(x)'); title('E3'); ylim([-3 3]) grid on

%save the picture
frame=getframe(gcf);
frames=[frames frame];

end

%display all the saved plots
while true

for iter = 1:length(frames)
imshow(frames(i).cdata);
drawnow;
pause(5);
end

end