2015-02-11 93 views
4

有没有一种简单的(理想情况下没有多个for循环)的方式来根据Matlab中的一组类别对值向量进行分组?Matlab将柱状数据转换为ndarray

我有数据矩阵形式

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 
    ... 

和我想是一个N维阵列

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

当然可以有任何数量的值使用相同的类别组合,因此size(end)将是最大类别中的值的数量 - 其余项目将填充nan

备选地我很高兴与

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

即矢量的一个单元阵列。我想这有点像创建一个数据透视表,但有n维,而不是计算mean

我发现这个功能在帮助

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

,但我无法捉摸如何使它做我想要的东西!

回答

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 

在你的例子,结果如下四维阵列:

>> 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 
+0

不错,我起初试过这个,但是被每个标签部分的累计计数卡住了。 @SanjayManohar这可能是更好的解决方案... – Dan 2015-02-11 15:54:38

+0

@丹谢谢。您的解决方案实际上在内存方面效率更高,因为它提供了单元阵列而不是N-D阵列 – 2015-02-11 15:58:58

+1

Perfect。还要感谢我介绍“unique”的第三个输出。 'ind'最终告诉每个项目“去哪里”,这真是可爱。 – 2015-02-11 16:01:25

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]

+1

哇 - 哇!这真是太神奇了。完美的作品。我会花一些时间研究你的代码。 Accumarray非常强大。 – 2015-02-11 15:54:06

+0

你真的需要'sz'作为单元阵列吗?你只用它作为'[sz {:}]' – 2015-02-11 15:55:48

+0

@LuisMendo我想不是那么... – Dan 2015-02-11 15:56:36