【问题标题】:How using reshape with cell arrays?如何使用单元阵列重塑?
【发布时间】:2014-11-28 12:29:03
【问题描述】:

不幸的是,我必须使用单元数组的数据集,它们甚至没有相同的输入.. 我的数据集(元胞数组的相关列)如下所示:

Data =
    1      'd2'      
    1      'd3'
    2      'u2'
    2      'd2'
    2      'u3'
    3      'e2'
    ...     ...

我想以某种方式重塑它们,即第一列中包含相同数字的所有行的第二列的所有输入都存储在新列中。因为第一列中每个数字的单行并不总是相同(但最高为 4),所以我编写了以下代码:

% creating 4 new cell arrays for the new columns
cells = cell(length(Data(:,1)),4);
Data = [Data,cells];

% reshaping Data
Data(:,3:6) = reshape(Data(Data(:,1) == 1,2),1,[]);
Data(:,3:6) = reshape(Data(Data(:,1) == 2,2),1,[]);

这可以完美地处理矩阵。但不幸的是,它不适用于单元阵列! 请你帮我,我必须把大括号放在哪里,这样它会起作用吗?到目前为止我还没有得到它,也许我现在只是在监督它! ;-)

非常感谢!

【问题讨论】:

  • 所以您想要像1 d2 d32 u2 d2 u3 等输出行?
  • 是的,就是这样

标签: matlab reshape cell-array


【解决方案1】:

我个人认为在这种情况下循环是最简单灵活的解决方案:

mydata={1     'd2'      
    1      'd3'
    2      'u2'
    2      'd2'
    2      'u3'
    3      'e2'}

list = unique([mydata{:,1}])
result = {};

for t=1:numel(list)
    count=0;
    for u =1:size(mydata,1)
        if mydata{u,1}==list(1,t)
            count = count+1;
            result(t,count)=mydata(u,2)
        end
    end
end

请注意,矢量化方法可能会更有效,但除非您的数据很大,否则它应该无关紧要。

【讨论】:

  • 你太棒了!非常感谢!!!这个for循环工作得很好!这对我帮助很大!
【解决方案2】:

这可能是一种使用 bsxfun 的屏蔽功能的方法 -

%// Input
Data = {
    1      'd2'      
    1      'd3'
    2      'u2'
    2      'd2'
    2      'u3'
    3      'e2'}

%// Find the IDs and the unique IDs
ids = cell2mat(Data(:,1))
id_out = num2cell([1:max(ids)]') %//'# To be used as the first col of desired o/p

%// Find the extents of each group/ID members
grp_extents = sum(bsxfun(@eq,[1:max(ids)],ids),1)
%// Or use accumarray which could be faster -
%//        grp_extents = accumarray(ids,ones(1,numel(ids))).'

%// Get a cell array with the members (strings) from the second column of Data 
%// put into specific columns based on their IDs 
string_out = cell(max(grp_extents),numel(grp_extents))
string_out(bsxfun(@le,[1:max(grp_extents)]',grp_extents)) = Data(:,2) %//'# This is 
                           %// where the masking is being used for logical indexing

%// Transpose the string cell array and horizontally concatenate with 1D
%// cell array containing the IDs to form the desired output
Data_out = [id_out string_out']

输出 -

Data_out = 
    [1]    'd2'    'd3'      []
    [2]    'u2'    'd2'    'u3'
    [3]    'e2'      []      []

【讨论】:

  • 我认为在速度很重要的情况下,这个解决方案会比我的更快。小备注:string_out 好像实际上不是字符串,所以我建议更改名称。
  • @DennisJaheruddin 嗯,string_out 更像是Data 第二列中字符串的元胞数组。我猜string_out_cell 可能是一个更好的名字,但是代码中的几乎所有内容都是单元格数组,所以我认为更愿意跳过这个术语cell,但从技术上讲,它不是一个字符串数组,而更像是一个单元格数组字符串。
猜你喜欢
  • 1970-01-01
  • 2021-08-31
  • 2015-09-21
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多