The location of the faulty programming:
S1=im2uint8 (Q2); % Q2 is the result of the treatment after the first picture, Q2 from 0 to 1 pixel matrix, this step is transformed into a scale of 0-255
S=double (S1); % the image data into a double, to get each image grey value matrix
A (:, :, I)=S; % to every one layer in a grey value matrix, a three dimensional matrix
On MATLAB show the cause of the error:

But in the fourth row, I define three dimensional matrix A is 2048 * 2048 * 51, not 2048 * 2048 * 2047
Matrix S store content and no problem

Can you tell me the problem is out in where