唯一不适用于具有NaN条目的表-MATLAB [英] Unique doesn't work with Table having NaN entries - MATLAB

查看:89
本文介绍了唯一不适用于具有NaN条目的表-MATLAB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个table,其中有重复的行,我尝试使用Matlab中的unique删除它们.但是,我不为所有这些人工作.这个玩具的例子说明了我的观点.关于如何删除的任何想法?

I have a table with duplicate rows that I try to remove with unique in Matlab. However, I doesnt work for all of them. This toy example illustrates my point. Any ideas of how, I remove them?

AAA = table(repmat('0122',2,1),repmat('011',2,1),repmat(NaN,2,1))

ans = 

    Var1    Var2    Var3
    ____    ____    ____

    0122    011     NaN 
    0122    011     NaN 

unique(AAA)

ans = 

    Var1    Var2    Var3
    ____    ____    ____

    0122    011     NaN 
    0122    011     NaN 

推荐答案

介绍性讨论

unique 上的Mathworks文档>指出以下内容-

Introductory Discussion

Mathworks documentation on unique states the following -

C = unique(A)返回与A中相同的数据,但没有 重复.

C = unique(A) returns the same data as in A, but with no repetitions.

如果A是表,则unique返回A中的唯一行.这 表C的行按排序顺序.

If A is a table, then unique returns the unique rows in A. The rows of table C are in sorted order.

因此,对于table作为unique的输入的情况,它表明它基本上类似于unique(....'rows'),只要您可以标识该表的每个条目.我们在这里使用的技巧是将所有这些条目转换为单元格数组的单元格,然后对每个单元格进行ID,然后将这些数字ID与unique(...'rows')一起使用.

So, for the case of table as input to unique, it suggests that it's basically like unique(....'rows'), if only you can ID each entry of that table. The trick we use here is to convert all those entries into cells of a cell array and then ID each cell and then use those numeric IDs with unique(...'rows').

接下来列出的代码就可以做到这一点-

The code listed next does just that -

function Tout = unique_table(T)

%// Convert input table into a cell array
Tcell = cellfun(@(x) num2str(x),table2cell(T),'Uni',0);

%// ID all cells of the cell array
[~,~,id_cells] = unique(Tcell);

%// Use the cell IDs to find the unique row IDs
[~,unq_rowid] = unique(reshape(id_cells,size(Tcell)),'rows');

%// Use the row IDs to get the expected table with unique rows
Tout = T(unq_rowid,:);

return;

测试运行

案例1:原始案例

T = 
    Var1    Var2    Var3
    ____    ____    ____
    0122    011     NaN 
    0122    011     NaN 
Tout = 
    Var1    Var2    Var3
    ____    ____    ____
    0122    011     NaN 

案例2:修改过的案例

T = 
    Var1    Var2    Var3
    ____    ____    ____
    0122    011      56 
    0122    011     NaN 
Tout = 
    Var1    Var2    Var3
    ____    ____    ____
    0122    011      56 
    0122    011     NaN 

这篇关于唯一不适用于具有NaN条目的表-MATLAB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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