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
| M = 0.5; m = 0.2; b = 0.1; I = 0.006; g = 9.8; l = 0.3; den = I*(M+m)+M*m*l^2; A = [0, 1, 0, 0; 0, -(I+m*l^2)*b/den, -(m^2*g*l^2)/den, 0; 0, 0, 0, 1; 0, (m*l*b)/den, m*g*l*(M+m)/den, 0]; B = [ 0; (I+m*l^2)/den; 0; -m*l/den]; C = [1, 0, 0, 0; 0, 0, 1, 0]; D = [0; 0]; sys_open = ss(A, B, C, D);
co = ctrb(sys_open); controllability = rank(co); poles = [-5; -10; -5+10j; -5-10j]; K = place(A, B, poles);
Ac = A-B*K; Bc = B; Cc = C; Dc = D; sys_closed = ss(Ac, Bc, Cc, Dc); x0 = [-0.2; 0; pi/4; 0]; t = 0:0.01:1.5; r = zeros(size(t)); y = lsim(sys_closed, r, t, x0); figure(1); plot(t, y(:, 1:2), 'LineWidth', 1.5); grid on legend('Cart position (m)', 'Pendulum angle (rad)'); title('Step Response with State-Feedback Control')
im = cell(length(t), 1); h = figure(2); for k = 1:length(t) x = y(k, 1); theta = y(k, 2); bot_x = x; bot_y = 0; top_x = x + l*sin(theta); top_y = l*cos(theta); plot(bot_x, bot_y, 'o', 'LineWidth', 1.5); hold on; plot([bot_x, top_x], [bot_y, top_y], 'LineWidth', 2); hold off; axis equal; axis([-0.5, 0.5, -0.10, 0.35]); grid on; title('Pendulum Animation') drawnow; frame = getframe(h); im{k} = frame2im(frame); pause(0.01); end
filename = 'pendulum_animation.gif'; for idx = 1:length(t) [A, map] = rgb2ind(im{idx}, 256); if idx == 1 imwrite(A, map, filename, 'gif', 'LoopCount', Inf, 'DelayTime', 1.00); else imwrite(A, map, filename, 'gif', 'WriteMode', 'append', 'DelayTime', 0.01); end end
|