Same reason knights in medieval battles carried daggers;
As a backup weapon, and for utility.
Battlefields are unpredictable, and no soldier will want to go into a situation where they might have to fight against someone who will have a total advantage. Imagine trying to direct ungainly arm/weapon pods of a mech while ducking and weaving at an enemy whose only a few feet away from you and doesn't have that limitation.
Molot makes good points about ammo conservation and the cost of shooting things, but if you're going to build mechs anyways, I feel cost can't be TOO much in the forefront of your mind.
An enemy mech that is melee equipped only has to swing his arm in your general direction when engaged at that range. If you get hit, even if it doesn't do much actual damage, your knocked about; your facing is probably changed, and your mech might very well end up on its butt and out of the fight. And, as with knights, someone quick and with a dagger was a real danger; they could get around you and shove it into one of the weak points of your armor quicker than you could turn to face them (especially) if you were bogged down in the terrain and they were not.
Melee weapons grow in effectiveness if the ranged weapons (guns, lasers, missiles) require multiple hits to penetrate/kill. The longer it takes to down the other person, the more chance they have to close that distance and knock you off target.
These type of encounters WILL happen in a limited visibility environment if both sides employ high mobility mechs; cities, fog banks, dust and rain storms. This is more endemic of warrior style combat then soldier style, where individuals and small groups engage without support, but is perfectly reasonable for commando style fights.
Another major factor is the utility of melee weapons for mechs. Maybe your “sword” is in reality a giant shovel; its main job is to dig trenches and help construct a forward operating base. Even current soldiers digging tools (E-Tools) can in an emergency double as a melee weapon. Knights used their daggers off the battle fields for various tasks, including to eat with, and while probably not ever expecting to have to use them on the battlefield, took them anyways because “just in case”.