【问题标题】:MATLAB: how to sort a matrix by a specific column name and also let the row names follow the order?MATLAB:如何按特定列名对矩阵进行排序,并让行名按照顺序排列?
【发布时间】:2014-07-03 07:45:03
【问题描述】:

我是 MATLAB 新手。我有一个名为da 的数据结构。我想对da.mat 的第一列进行排序,并想让da.rid 和其他列遵循重新排列的顺序。 da.cid 包含列名,da.rid 包含行 ID。

da = 
    mat: [22268x377 single]
    rid: {22268x1 cell}
    rhd: {''}
  rdesc: {22268x1 cell}
    cid: {377x1 cell}
    chd: {0x1 cell}
  cdesc: {377x0 cell}

另外,如果我想使用其他列而不是da.mat 的第一列并且我将从da.cid 获得,我该如何实现呢? 例如,如果我想在cid 中查找列名'A02' 并使用它来选择da.mat 的特定列进行排序。请你帮助我好吗?谢谢。

木头

【问题讨论】:

  • 感谢您的评论。我的问题实际上非常不同。我想对数据结构中的一列进行排序,并使其他列(尤其是 rid)遵循相同的顺序。
  • 我撤回了我的副本
  • other columns 是什么意思?那是other其他字段的列?如果是这样,那怎么可能,因为其他字段的大小与da.mat不同。
  • 是的,我指的是 da.mat 本身的其他列。

标签: matlab sorting indexing cell-array


【解决方案1】:

假设其他列,你的意思是da.mat本身的其他列,你可以试试这个-

[val,ind] = sort(da.mat(:,1))
da.mat = da.mat(ind,:)
da.rid = da.rid(ind)

如果您希望使用其他列号而不是 1 进行排序并基于字段 cid 中的名称,请使用此 -

cid_matchcol =  'A02'; %// column name to be used from `da.cid` to choose column of `da.mat`

base_col = find(strcmp(da.cid,cid_matchcol),1)
[val,ind] = sort(da.mat(:,base_col))
da.mat = da.mat(ind,:)
da.rid = da.rid(ind)

【讨论】:

  • 通过使用 da.mat(:,1) 对第一列进行排序,您提取了它的值和索引。然后,您将索引分配给 rid。是的,这就是我想要的!谢谢!!
  • 嗨 Divakar,您能否更详细地解释一下 da.mat(ind,:) 的作用? ind 不只是索引吗? matlab怎么知道要排序哪一列?
  • da.mat(ind,:): 告诉 MATLAB 对所有列进行排序。如果我写了da.mat(ind,2),它将只对第二列进行排序,da.mat(ind,3) 对第三列进行排序,依此类推。
  • 另外,我可以用 cid 为 sort(da.mat(:,1)) 指定列名吗?
  • 列名还是列号?
猜你喜欢
  • 1970-01-01
  • 2016-10-27
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
相关资源
最近更新 更多