MATLAB按值分组数据表:将Value2按Value1归类
问题描述
我有一个包含各类数值的数据表:
| Value 1 | Value 2 |
|---|---|
| 0 | 235 |
| 1 | 123 |
| 1 | 309 |
| 1 | 540 |
| 2 | 34 |
| 3 | 123 |
| 3 | 959 |
| 3 | 3939 |
希望得到按Value 1的每个值对Value 2进行归类的数据表,格式如下:
| Value 1 | Value 2 |
|---|---|
| 0 | [235] |
| 1 | [123, 309, 540] |
| 2 | [34] |
| 3 | [123, 959, 3939] |
或类似格式。
我尝试了几种解决方案但均未成功:
t = table; for i=1:length(existing_table) t(existing_table, end+1) = existing_table.value2(i) % append to case i end;
返回错误:
Error using ()
Right hand side of an assignment into a table must be another table or a cell array.
t = table; for i=1:length(existing_table) switch existing_table.value2(i) case 0 t(0, end+1) = existing_table.value2(i) % append to case 0 % etc... end; end;
返回错误:
Error using ()
Right hand side of an assignment into a table must be another table or a cell array.
t = table; t.v1 = value1; t.v2 = unique(value2) % 未得到期望格式的表格
解决方案
方法1:使用findgroups + splitapply(推荐)
利用MATLAB内置的分组聚合函数,简洁高效实现需求:
% 假设原始表名为existing_table [group_ids, unique_v1] = findgroups(existing_table.Value1); % 定义聚合函数,将每组Value2打包为数组 aggregate_func = @(x) {x}; v2_groups = splitapply(aggregate_func, existing_table.Value2, group_ids); % 构建结果表格 result_table = table(unique_v1, v2_groups, 'VariableNames', {'Value1', 'Value2'});
运行后result_table的Value2列是单元格数组,每个单元格对应一组的数值列表,完全符合需求格式。
方法2:手动循环(修正你的错误)
如果想用循环实现,需要注意MATLAB的表格规则和索引逻辑,修正后的代码:
% 获取Value1的唯一值并排序 unique_v1 = unique(existing_table.Value1); % 初始化结果表格,Value2列为单元格类型 result_table = table(unique_v1, cell(length(unique_v1),1), 'VariableNames', {'Value1', 'Value2'}); for i = 1:length(unique_v1) % 筛选当前Value1对应的所有Value2 current_v2 = existing_table.Value2(existing_table.Value1 == unique_v1(i)); % 以单元格形式赋值 result_table.Value2(i) = {current_v2}; end
错误原因解释
- 直接将单个数值赋值给表格列:MATLAB要求表格赋值的右侧必须是表格或单元格数组,单个数值不符合要求,因此报错
- 使用无效索引:MATLAB的数组/表格索引从1开始,
t(0, end+1)中的0行索引是非法的 unique(value2)仅获取Value2的唯一值,没有按Value1分组,因此无法得到归类后的格式
内容的提问来源于stack exchange,提问作者C. Crt
相关产品推荐
相关产品推荐

