MATLAB: How to store matrices into a cell array in the correct order

cell arrayssort

I'm trying to store a set of matrices that are generated using a for loop. The structure of the code is
for k = 1:N % loops through some folders - a few commands go in here for sorting the folders
for kk = n:-1:1 % loops through the files in each folder in reverse - the files are csvs that contain two columns of data. I then use the find peaks function on this data and for each file store a matrix
matrix = [loc height]; % this stores the position of each peak and its height - for each file this may have a different number of rows as they do not all have the same number of peaks
cellarray{kk} = matrix; % Should store each matrix in a cell array
end
end
When I store the cell array, for some reason the elements are stored in reverse order. The matrix from the first file that the code loops through is the last cell in the cell array. I can't think of a good reason why this should be the case, other than maybe it is to do with the fact that I am looping through the files in reverse. If I look at matrix, matrix(1) is a 6×2 matrix and matrix(end) is a 1×2 matrix, but in the cell array, the first cell is 1×2 and the last cell is 6×2. Why is this the case and what can I do about it? If I reverse the order of the kk iterations, it loops through matrix in the reverse order but store cellarray in the same way.

Best Answer

"When I store the cell array, for some reason the elements are stored in reverse order."
Not at all. They are stored in the exact order that you specify using indexing, as I explained earlier:
which has nothing to do with which one you define first or last. Index 1 is always index 1, no matter when you assign to it. Lets go through two simple examples step by step, first in descending order, like your code:
C = nan(1,5);
for k = 5:-1:1 % descending order
C(k) = k^2;
end
The loop iterations are:
  1. assign 5^2 to C(5)
  2. assign 4^2 to C(4)
  3. assign 3^2 to C(3)
  4. assign 2^2 to C(2)
  5. assign 1^2 to C(1)
giving the vector [1,4,9,16,25]. Now lets do it in asending order:
D = nan(1,5);
for k = 1:5 % ascending order
D(k) = k^2;
end
The loop iterations are:
  1. assign 1^2 to D(1)
  2. assign 2^2 to D(2)
  3. assign 3^2 to D(3)
  4. assign 4^2 to D(4)
  5. assign 5^2 to D(5)
giving the vector [1,4,9,16,25]. Because our iterations are totally independent of one another, their order of calculation is totally irrelevant. Whether ascending or descending in the loop, we get the same output vector.
Of course if you want to change the indices then you have to change the indices (not the order of the loop iterations, which makes no difference):
C = cell(1,n);
for kk = 1:n
C{n-kk+1} = your data
end
Or perhaps simpler to reverse afterwards:
C = cell(1,n);
for kk = 1:n
C{kk} = your data
end
C(end:-1:1) = C(:)
which is exactly what I showed you one day ago: