A new approach to compute optimal forcing functions for nonlinear dynamic systems expressed by differential equations and stemming from the sliding mode control (SMC) problems is presented. SMC input achieves generation of a desired trajectory in two phases. In the first phase, the input is designed to steer the state of the nonlinear dynamic system towards a stable (hyper) surface (in practice, it is generally a subspace) in the state space. The second phase starts once the state enters a prespecified neighbourhood of the surface. In this phase, the control input is required to drive the system state towards the origin while keeping it in this neighbourhood. It is shown that by appropriate selection of the objective functions and the constraints, it is possible to model both phases of this problem in the form of constrained optimization problems, which provide an optimal solution direction and thus improve the chattering. Generally, these problems are not convex and therefore require a special solution approach. The modified subgradient algorithm, which serves for solving a large class of nonconvex optimization problems, is used here for solving the optimization problems so constructed. This article also proposes a generalized optimization problem with a unified objective function by taking a weighted sum of two objectives representing the two stages. Validity of the approach of this work is illustrated by stabilizing a two-link planar robot manipulator.