Unique does not work with table having NaN - MATLAB entries

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

Introductory Discussion

Mathworks documentation on unique states the following -

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

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

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') .

Function Code

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;

Test runs

Case #1: Original case

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

Case #2: Modified case

T =
    Var1    Var2    Var3
    ____    ____    ____
    0122    011      56
    0122    011     NaN
Tout =
    Var1    Var2    Var3
    ____    ____    ____
    0122    011      56
    0122    011     NaN
我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章