How do I store matrices into a cell array in the correct order?
Afficher commentaires plus anciens
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 6x2 matrix and matrix(end) is a 1x2 matrix, but in the cell array, the first cell is 1x2 and the last cell is 6x2. 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.
2 commentaires
Rik
le 7 Déc 2018
You are not showing your complete code, which makes it hard to come up with definitive answers. It looks like the kk counter determines which file you analyze and which cell position the results are stored in. That means that reversing the loop doesn't change the ordering of the cell array, just the order in which it is filled. If you want to store them in reverse order you will need something like this:
A=1:5;
B=zeros(size(A));
for n=numel(A):-1:1
B(numel(A)-n+1)=A(n);
end
Jan
le 7 Déc 2018
@JJH: This piece of code overwrites the elements of cellarray in each iteration of the outer loop. Is this intented?
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!