The first step when analyzing any character's purpose in a play, is to have a clear grasp of the play's structural base, so that the character might be seen as filling a necessary role within that structure. Hamlet is a tragedy, and, as such, requires a tragic hero who suffers from a flaw that is the instrument of his own demise. Most tragic heroes recognize their flaw as the reason for their own demise, rather than blaming it on outside events.
Hamlet's purpose is to serve as the play's tragic hero, and his flaw is his own hesitation, his inclination to analyze and consider to excess, rather than react and take action to kill Claudius immediately. This flaw sets in motion the complications, the events that come out of Hamlet's inability to act swiftly and directly against Claudius, most notably, the death of Polonius. From this death comes the madness and death of Ophelia; the anger and action-oriented reaction of Laertes (a foil to the inaction of Hamlet at the murder of his own father); and the banishment of Hamlet and deaths of Rosencrantz and Guildenstern; not to mention the final bloodbath that ensues from the duel instigated by Laertes and Claudius -- all in response to Polonius' death.
Of course, Hamlet's inaction also assists in the tension and suspense created in the play. When will he finally rise up and strike? The audience is able to wonder this throughout the play.
So, Hamlet's purpose is to serve as the tragic hero of the play, his inaction (and the act of murdering Polonius) creating a major portion of the play's complications and tension. For more on Hamlet's purpose in the play, please consult the links below.