%% Chapter M-File for Simulink Chapter (Chapter 9)

%% Section 9.1
%
% The first part of this section is about assembly of a model.
% The final products are |dampedosc.slx| and |dampedoscinhom.slx|.
% Figures 9.3-9.4 are produced with:
open_system('firststage')
set_param('firststage','PaperOrientation','portrait')
print -s -dpng dampedosc1.png
close_system('firststage')
open_system('secondstage')
set_param('secondstage','PaperOrientation','portrait')
print -s -dpng dampedosc2.png
close_system('secondstage')
%%
% Figure 9.5 of the finished model is produced with a screenshot.
open_system('dampedosc')
set_param('dampedosc','PaperOrientation','portrait')
%%
% Figure 9.7 is produced with:
set_param('dampedoscinhom','PaperOrientation','portrait')
print -sdampedosc -dpng dampedoscinhom.png
%%
% Figures 9.6 and 9.8 can be produced with
sim('dampedosc')
sim('dampedoscinhom')
close_system('dampedosc')
close_system('dampedoscinhom')

%% Section 8.2
%
% The first part of this section is about assembly of a model for a crane.
% The final product is |crane.mdl|. We need the following calculation:
syms t a b c;
w = 5 + a*(t-100) + b*(t-100)^3 + c*(t-100)^5;
w0 = subs(w, t, 0);
w1 = subs(diff(w,t), t, 0);
w2 = subs(diff(w,t,2), t, 0);
[aa, bb, cc] = solve(w0, w1, w2);
w = subs(w, [a,b,c], [aa,bb,cc])
diff(w, t, 2)
%%
% Figure 9.10 is produced with
ezplot(w, [0, 200]), axis([0, 200, 0, 10]), title 'w(t)'
print -deps wfunc.eps
%%
% Figures 9.11 and 9.12
open_system('crane')
set_param('crane','PaperOrientation','portrait')
print -s -dpng cranemodel.png
sim('crane')

%% Section 8.3
%
w = simplify(subs(w, t, 10*t))
simplify(diff(w, t, 2))
%%
gcs
find_system(gcs, 'Type', 'block')
get_param('crane/w"', 'Expr')
set_param('crane/w"', 'Expr', '3*u*(u - 10)*(u - 20)/8000')
craneout = sim('crane', 'SaveTime','on','TimeSaveName','t', ...
   'SaveState','on','StateSaveName','theta','StopTime', '20');
t = craneout.find('t'); theta = craneout.find('theta');
plot (t, theta)
print -deps craneoutput.eps
%%
simplot (t, theta(:,1))
set(gcf,'InvertHardcopy','off')
print -deps cranesimplot.eps
