Remove this line legend('-DynamicLegend'); and write it just before the drawnow line and write hold off after that line. So the following will be the lines at the end of your loop.
legend('-DynamicLegend');
drawnow;
hold off
index=index+1;
0
solved How to Get Dynamic Legend on Linear Graph in Loop?