MATLAB: Saving dat from a loop

loop formatrixsaving data

Hello, I am saving a matrix which is calculated inside a loop and I am putting all these n matrix inside another matrix with matrix element. I have trouble because it saves just the last matrix calculated from the loop; If I print all these matrixes the code works well. Any suggestions?
Thanks in advance

Best Answer

for K = 1 : 5
Output(:,:,K) = magic(7) - K.^2;
end
Output(:,:,1)
ans = 7×7
29 38 47 0 9 18 27 37 46 6 8 17 26 28 45 5 7 16 25 34 36 4 13 15 24 33 35 44 12 14 23 32 41 43 3 20 22 31 40 42 2 11 21 30 39 48 1 10 19
Output(:,:,end)
ans = 7×7
5 14 23 -24 -15 -6 3 13 22 -18 -16 -7 2 4 21 -19 -17 -8 1 10 12 -20 -11 -9 0 9 11 20 -12 -10 -1 8 17 19 -21 -4 -2 7 16 18 -22 -13 -3 6 15 24 -23 -14 -5
As you can see we have been successful in storing different matrices along the third dimension.