How does a spacecraft turn from photographing the Moon to relaying data and then recharging its batteries?
Building the MATLAB model
Start with the body frame
I defined the geometry of a 4 kg, MinXSS-inspired spacecraft and assigned an axis to each pointing task. I wrote and checked conversions between direction cosine matrices, quaternions and 3-2-1 Euler angles so the orbit, sensors and controller could share a consistent frame.

Couple translation and rotation
I integrated a two-body lunar orbit with MATLAB’s ode45, then propagated angular velocity with Euler’s rigid-body equations and attitude with quaternion kinematics. I joined the two models and added gravity-gradient torque so the spacecraft’s orientation and position both affected the rotational dynamics.
Estimate attitude and close the loop
I used TRIAD to estimate orientation from noisy Sun-sensor and lunar-horizon measurements. I built moving reference frames for the three targets, tested a detumble controller and used gyro feedback and gravity-gradient compensation to command torque during pointing.
Check what should stay constant
In a two-body orbit, total orbital energy should stay constant. I plotted the difference from its initial value over 12,000 seconds. At a solver tolerance of 10⁻² the energy drifts downward. The 10⁻⁶ and 10⁻¹² traces overlap near zero at the scale shown.

I made a separate conservation check with gravity-gradient and control torques switched off. Rotational kinetic energy should remain constant as angular velocity changes in the body frame. I also checked quaternion magnitude during propagation.
The 7,500-second mission
I carried the final state of each phase into the next. At each handoff the spacecraft kept its attitude and angular velocity while the controller received a new pointing reference.

When the controller worked hardest
Figure 23 shows the three commanded torque components in N·m. Short bursts appear at startup and at the dashed switches at 2,500 and 5,000 seconds. Additional spikes occur within the relay and recharge phases. Between bursts the commands lie close to zero on this scale.

How the pointing error evolved
Figure 24 shows the dimensionless scalar and three vector components of the error quaternion. The scalar returns toward one after large excursions, while the vector components shrink with some residual offsets. The original image crops the time-axis labels. Figure 23 supplies the phase timing.
Reading the results
The model treats the spacecraft as a rigid body in a two-body lunar orbit with gravity-gradient torque, modeled actuators and simulated sensor noise. Gateway position data and a Sun direction define the relay and recharge targets.
The plots describe simulated attitude error and control effort. Assessing image quality, data throughput or battery charge would require separate payload, link or power models.