# The Martian – Part 2 – Simulating the Spacecraft Trajectory

In last week's post, I demonstrated how we can use MATLAB to find the launch date of the Ares 3 crew from the book The Martian, by Andy Weir.

This week, I will describe in more detail how we can use SimMechanics to simulate the trajectory of the spacecraft.

Next week, we will talk about how we can use the Optimization Toolbox to optimize the trajectory.

Sorry Mark Watney ... One more week before being rescued.

Simulating the Trajectory

To implement this simulator, I used SimMechanics. I started with the example Planetary Orbit Due to Gravity, which provides almost everything needed.

To keep things simple, I decided to begin with a planar version, so I used Rectangular Joints.

After setting the inertia of each planet, all that is left is to specify the initial positions and velocities of the joints. To obtain this information, we can use the Aerospace Toolbox function planetEphemeris.

As pointed out by reader Brandon, the rotational axes of Mars and Earth are tilted by about 24 degrees relative to the reference frame of the JPL planetary ephemerides returned by planetEphemeris. Since I wanted to go with a planar simulation, I first needed to rotate the data. I did it using the following code, taking the cross product of the two positions to get the axis around which Earth rotates, and project it onto the reference Z axis to get the exact tilt angle:

After multiplying the data from planetEphemeris by the rotation matrix, we have an orbit purely in the X-Y plane.

Well, it is Rocket Science...

For the propulsion system, the spacecraft is equipped with a constant-thrust engine capable of producing 2 mm/s^2 of acceleration continuously. This force is applied using the External Force and Torque block, connected to the ship frame.

With all that in place, I was able to manually select the directions (over time) to apply the constant force that could get the ship not too far from Mars in the same number of days described in the book. This trajectory will be used next week as starting point for the optimization problem.