【问题标题】:Deleting and retaining data in a cell array -Matlab删除和保留单元格数组中的数据 -Matlab
【发布时间】:2015-11-11 16:08:22
【问题描述】:

我在一个单元格数组中有一组数据,其中一部分如下所示。第 2 行和第 3 行的前三列相同。从第 4 列开始的第 2 行中,它包含已捕获的 P0702在第 3 行(前三列与第 2 行相同)。所以我想删除第 2 行。同样,第 5 行和第 6 行在前三列中具有相同的数据。第五行中的 P0882 和 P0702 也存在于第六行,所以我想删除第五行。

重复前的数据

'1FA'   2   'Fm'    []      []      []      []      []  []  []  'P2700' []
'1Fc'   2   'Fz'    []      []      []      'P0702' []  []  []  []      []
'1Fc'   2   'Fz'    []     'P0702'  'P0801' []      []  []  []  []      []
'1Fj'   8   'Fr'    'P0702' []      []      []      []  []  []  []      []
'1FAH'  2   'Fo'    []  []  []  []  []  []  'P0882' 'P0702' []
'1FAH'  2   'Fo'    []  []  []  []  []  []  'P0882' 'P0702' 'P2700' 

复制后的数据

    '1FA'   2   'Fm'    []      []      []      []  []  []  []  'P2700' []

    '1Fc'   2   'Fz'    []      'P0702' 'P0801' []  []  []  []  []      []
    '1Fj'   8   'Fr'    'P0702' []      []      []  []  []  []  []      []

    '1FAH'  2   'Fo'    []  []  []  []  []  []  'P0882' 'P0702' 'P2700' 

任何帮助都会很好。

【问题讨论】:

  • 发现重复时,总是删除第一行?
  • @Daniel-不一定,在这种情况下我删除了,因为与第 2 行和第 5 行相比,第 3 行和第 6 行捕获了一些额外的数据(P0801-第 3 行)和 P2700-第 6 行) .
  • 始终保留包含最多非空单元格的行?

标签: matlab cell-array


【解决方案1】:

首先阅读问题,我认为这应该可以用 2 或 3 行来解决,但需要几行代码才能解决:

M={'1FA'   2   'Fm'    []      []      []      []      []  []  []  'P2700' []
'1Fc'   2   'Fz'    []      []      []      'P0702' []  []  []  []      []
'1Fc'   2   'Fz'    []     'P0702'  'P0801' []      []  []  []  []      []
'1Fj'   8   'Fr'    'P0702' []      []      []      []  []  []  []      []
'1FAH'  2   'Fo'    []  []  []  []  []  []  'P0882' 'P0702' []
'1FAH'  2   'Fo'    []  []  []  []  []  []  'P0882' 'P0702' 'P2700' }

%r contains the number of nonempty cells, you want those with highest r
r=sum(cellfun(@(x)~isempty(x),(M(:,4:end))),2);
%Create a index matrix which maps each string of first and third column to
%a double, which allows to use unique.
[~,~,index]=unique(M(:,1));
index(:,2)=[M{:,2}];
[~,~,index(:,3)]=unique(M(:,3));
%fill fourth colum with consecutive numbers, used to restore original
%ordering
index(:,4)=1:size(index,1);
%Next two lines, sort index to have rows with highetst r first
[~,sorted_most_content]=sort(-r);
index=index(sorted_most_content,:);
%Now first three columns of index should be unique and the best choice
%comes first, finally unique can be used.
[~,indices_unique_content,~]=unique(index(:,1:3),'rows');
%use previously appended consecutive numbers to get line numbers we want.
%sort restores original ordering.
unique_content_inorder=sort(index(indices_unique_content,4));
%The data you want:
M(unique_content_inorder,:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多