It might be because you manipulated variables using "clear". "clear" will delete all vriables, including the loop counters.
I would suggest that you use a 3D matrix (3 layers of loops) to keep all the data. At the end of the simulation you save the data, if the data file is not very large. Later you can load/read the data for further processing.
Or you can reuse the matrix instead of clear it since you have already saved the data.
DO not use "clear" in the middle of the script. Only use it before any variables.