重塑Matlab表 [英] Reshape Matlab table

查看:57
本文介绍了重塑Matlab表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表

name = ['A' 'A' 'A' 'B' 'B' 'C' 'C' 'C' 'C' 'D' 'D' 'E' 'E' 'E']';
value = randn(14, 1);
T = table(name, value);

i.e.

T = 

name      value  
____    _________

A       0.0015678
A        -0.76226
A         0.98404
B         -1.0942
B         0.71249
C           1.688
C          1.4001
C         -0.9278
C         -1.3725
D         0.11563
D        0.076776
E          1.0568
E          1.1972
E         0.29037

我想通过以下方式对其进行转换:取value中的前两个单元格对应于name中的不同值,并将其放入5x2矩阵中.该矩阵将具有对应于不同名称A,B,C,D,E的行和对应于values的列,例如.前两行是

I want to transform it in the following way: take the first two cells in value corresponding to different values in name and put it in the 5x2 matrix. This matrix would have rows corresponding to different names A,B,C,D,E and columns corresponding to values, e.g. the first two rows are

0.0015678 -0.76226
-1.0942    0.71249

推荐答案

这可以通过 accumarray 使用自定义函数.第一步是将Tname列转换为数字矢量;然后可以应用accumarray.

This can be done with accumarray using a custom function. The first step is to convert the name column of T into a numeric vector; and then accumarray can be applied.

此方法要求根据第1列对T进行排序,因为只有在这种情况下,accumarray才能保证保留顺序(如其文档中所示).因此,如果T可能没有排序(尽管在您的示例中是),请首先使用 sortrows .

This approach requires T being sorted according to column 1, because only in this case is accumarray guaranteed to preserve order (as indicated in its documentation). So if T may not be sorted (although it is in your example), sort it first using sortrows.

T = sortrows(T, 1); %// you can remove this line if T is guaranteed to be sorted
[~, ~, names] = unique(T(:,1)); %// names as a numeric vector
result = cell2mat(accumarray(names, T.value, [], @(x) {x([1 2]).'}));

这篇关于重塑Matlab表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆