This paper deals with the optimal tracking problem for switched systems, where the control input, the switching times and the switching index are all design variables. We propose a three-stage method for solving this problem. First, we fix the switching times and switching index sequence, which leads to a linear tracking problem, except different subsystems are defined in their respective time intervals. The optimal control and the corresponding cost function obtained depend on the switching signal. This gives rise to an optimal parameter selection problem for which the switching instants and the switching index are to be chosen optimally. In the second stage, the switching index is fixed. A reverse time transformation followed by a time scaling transform are introduced to convert this subproblem into an equivalent standard optimal parameter selection problem. The gradient formula of the cost function is derived. Then the discrete filled function is used in the third stage to search for the optimal switching index. On this basis, a computational method, which combines a gradient-based method, a local search algorithm and a filled function method, is developed for solving this problem. A numerical exampleis solved, showing the effectiveness of the proposed approach.