To build a wireless capsule endoscope with active external guidance for controllable and interactive diagnosis on the gastrointestinal tract, it is necessary to track the capsule's 3-D position and 3-D orientation. An approach to tracking is to enclose a small rectangular permanent magnet in the capsule. The magnetic field produced around the body by the rectangular magnet can be detected by magnetic sensors outside the patient's body. With these detected magnetic sensor data, the 3-D localization and 3-D orientation parameters can be computed by an appropriate algorithm based on the mathematical model of the rectangular magnet's magnetic field. We tried several nonlinear optimization algorithms, and simulation experiments show that the particle swarm optimization algorithm can work effectively with good accuracy when the magnet moves within a predetermined range.