Matlab converts column data to ndarray

Is there a simple (ideally without multiple for the loop) way of grouping the vector of values ​​according to the set of categories in Matlab?

I have a data matrix in the form

CATEG_A    CATEG_B   CATEG_C  ...   VALUE

   1          1        1      ...   0.64
   1          2        1      ...   0.86
   1          1        1      ...   0.74
   1          1        2      ...   0.56
  ...

and etc.

and I want an N-dimensional array

 all_VALUE( CATEG_A, CATEG_B, CATEG_C, ..., index ) = VALUE_i

Of course, there can be any number of values ​​with the same combination of categories, therefore it size(end)will be the number of the value in the largest category, and the remaining elements will be supplemented nan.

Alternatively, I would be happy

 all_VALUE { CATEG_A, CATEG_B, CATEG_C, ... } ( index )

i.e. an array of vector cells. I suppose this is similar to creating a pivot table, but with n dimensions, not a calculation mean.

I found this function in the help

A = accumarray(subs,val,[],@(x) {x})

but I could not figure out how to get him to do what I wanted!

+4
2

, . ND-.

X = [1        1        1        0.64
     1        2        1        0.86
     1        1        1        0.74
     1        1        2        0.56]; %// data
N = size(X,1); %// number of values
[~, ~, label] = unique(X(:,1:end-1),'rows'); %// unique labels for indices
cumLabel = cumsum(sparse(1:N, label, 1),1); %// used for generating a cumulative count
    %// for each label. The trick here is to separate each label in a different column
lastInd = full(cumLabel((1:N).'+(label-1)*N)); %'// pick appropriate values from 
    %// cumLabel to generate the cumulative count, which will be used as last index
    %// for the result array
sizeY = [max(X(:,1:end-1),[],1) max(lastInd)]; %// size of result
Y = NaN(sizeY); %// initiallize result with NaNs
ind = mat2cell([X(:,1:end-1) lastInd], ones(1,N)); %// needed for comma-separated list
Y(sub2ind(sizeY, ind{:})) = X(:,end); %// linear indexing of values into Y

4D:

>> Y
Y(:,:,1,1) =
    0.6400    0.8600
Y(:,:,2,1) =
    0.5600       NaN
Y(:,:,1,2) =
    0.7400       NaN
Y(:,:,2,2) =
   NaN   NaN
+2

,

[U,~,subs] = unique(X(:,1:end-1),'rows');

sz = max(U);
Uc = mat2cell(U, size(U,1), ones(1,size(U,2)));
%// Uc is converted to cell matrices so that we can take advantage of the {:} notation which returns a comma-separated-list which allows us to pass a dynamic number of arguments to functions like sub2ind

I = sub2ind(sz, Uc{:});

G = accumarray(subs, X(:,end),[],@(x){x});

A{prod(max(U))} = [];  %// Pre-assign the correct number of cells to A so we can reshape later
A(I) = G;
reshape(A, sz)

( ... s), :

A(:,:,1) = 

    [2x1 double]    [0.8600]


A(:,:,2) = 

    [0.5600]    []

A(1,1,1) [0.74; 0.64]

+2

All Articles