how do i take the data from cells in a cell array and turn them into a data array

i am writing a data anylsis script where I import an excell file, sort the data in that file by the first column then seperate out all the rows that have the same value into their out matrices. So far i have been able to sort all rows that have the same values in column one into individul cells in a cell array
[u,~,ib] = unique(T1(:,1));
[M,~] = size(u);
C = cell(1,M);
clear M
for i = 1:length(u)
C(i) = {T1(ib==i,:)};
end
[~,N] = size(C); % how many cells are in the array
Now i want to extract those values out of the cells into individual data arrays but i dont know how many arrays i will need.
i know that to convert a cell array to a data matrix i would use
Ai = cell2mat(C{i})
i mainly want to know how to create as many "A" matrices as required with out knowing how large "N" is before hand

4 comentarios

Do not split out C into N different variables! Simply use C{k} to get the k-th dta set.
Bob Thompson
Bob Thompson el 30 de En. de 2019
Editada: Bob Thompson el 30 de En. de 2019
Why do you need to create a bunch of different matrices? Handling a series of variables is significantly more difficult than leaving the arrays indexed within C and calling the appropriate cell contents.
If you really do need to create a series of matrices like that, then the only way I know how to is to use a for loop, but you cannot create a unique variable name within a loop, so you will have to create a temporary variable, and then output it to a file, or some similar process.
for i = 1:length(C) % Size is unnecessary because C is only one dimensional
A = cell2mat(C{i});
xlswrite(['output',num2str(i),'.xlsx'],A);
end
if you want to store them in separate matrices use 3D matrix but don’t think of naming variables dynamically!
Simpler:
[u,~,ib] = unique(T1(:,1));
N = numel(u);
C = cell(1,N);
for k = 1:N
C{k} = T1(ib==k,:);
end
or even using accumarray. The simplest and most effiicient way to store and access those matrices is to use a cell array. Naming variables dynamically is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:

Iniciar sesión para comentar.

Respuestas (1)

This is the accumarray solution that Stephen hinted to:
T1 = [99 10 11 ; 99 20 21 ; 30 31 32]
[~,~,ib] = unique(T1(:,1), 'stable')
C = accumarray(ib, 1:size(T1,1), [], @(k) {T1(k,:)})

Categorías

Etiquetas

Preguntada:

el 30 de En. de 2019

Respondida:

el 31 de En. de 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by