That was the point Jan and Walter made in the previous posting -- reopening/reposition a file does not delete any existing content of the file so that if you make changes and rewrite data that is shorter than what was there before, everything from the last character you write forward is still in the file.
If you want entirely new content in the file, the only reliable was in Matlab is to close and reopen it. Otherwise, you'll get the desired result if the new file content is as long or longer than the original, but if shorter, then you get the result you see.
It was possible in the original code you showed to have computed the wrong size but that is, while a coding error, a diversion from the more fundamental issue.