%% Create Joint-Space Motion Model
% This example shows how to create and use a jointSpaceMotionModel object for a manipulator robot in joint-space.
%% Create the Robot

robot = loadrobot("kinovaGen3","DataFormat","column","Gravity",[0 0 -9.81]);

%
%% Set Up the Simulation
% Set the timespan to be 1 s with a timestep size of 0.01 s. Set the initial state to be the robots, home configuration with a velocity of zero.

tspan = 0:0.01:1;
initialState = [homeConfiguration(robot); zeros(7,1)];

% Define the a reference state with a target position, zero velocity, and zero acceleration.

targetState = [pi/4; pi/3; pi/2; -pi/3; pi/4; -pi/4; 3*pi/4; zeros(7,1); zeros(7,1)];

%% Create the Motion Model
% Model the system with computed torque control and error dynamics defined by a moderately fast step response with 5% overshoot.

motionModel = jointSpaceMotionModel("RigidBodyTree",robot);
updateErrorDynamicsFromStep(motionModel,.3,.05);

%% Simulate the Robot
% Use the derivative function of the model as the input to the ode45 solver to simulate the behavior over 1 second.

[t,robotState] = ode45(@(t,state)derivative(motionModel,state,targetState),tspan,initialState);

%% Plot the Response
% Plot the positions of all the joints actuating to their target state. Joints with a higher displacement between the starting position and the target position actuate to the target at a faster rate than those with a lower displacement. This leads to an overshoot, but all of the joints have the same settling time.

figure
plot(t,robotState(:,1:motionModel.NumJoints));
hold all;
plot(t,targetState(1:motionModel.NumJoints)*ones(1,length(t)),"--");
title("Joint Position (Solid) vs Reference (Dashed)");
xlabel("Time (s)")
ylabel("Position (rad)");

%
% Copyright 2019 The MathWorks, Inc.