Collapse logical table into cell strings that contains the table's variable names

1 回表示 (過去 30 日間)
I have a n x m logical truth table in the format where "a b c d" are the table variable names
exampleTable =
5×4 table
a b c d
_____ _____ _____ _____
false false false false
true true true true
false false true true
true false true false
false false false true
and I would like to collapse it into a cell array of height n like below. Each row n is a cell array of strings that contains the name of the variable (column) when the entry is true
{{''}; {'a','b','c','d'}; { 'c','d'}; { 'a','c'}; {'c'}}
I imagine I can do something with cellfun, but I'm a little stuck. Thanks for your help!

採用された回答

Walter Roberson
Walter Roberson 2022 年 1 月 6 日
temp = [ false false false false
true true true true
false false true true
true false true false
false false false true ];
exampleTable = array2table(temp, 'VariableNames', {'a', 'b', 'c', 'd'})
exampleTable = 5×4 table
a b c d _____ _____ _____ _____ false false false false true true true true false false true true true false true false false false false true
varnames = exampleTable.Properties.VariableNames;
output = rowfun(@(r) varnames(r), exampleTable, 'SeparateInputs', false, 'OutputFormat', 'cell')
output = 5×1 cell array
{1×0 cell} {1×4 cell} {1×2 cell} {1×2 cell} {1×1 cell}
output{2}
ans = 1×4 cell array
{'a'} {'b'} {'c'} {'d'}
  3 件のコメント
Michael Shagam
Michael Shagam 2022 年 1 月 6 日
編集済み: Michael Shagam 2022 年 1 月 6 日
@Walter Roberson followup question. In some later existing code, I use ismember() to do a generic query for a condition. I was hoping to be able to do something like shown to return a true when a row contains an 'a' and/or 'c', but I get this error
ismember(output, {'a' 'c'})
Error using cell/ismember (line 34)
Input A of class cell and input B of class cell must be cell arrays of character vectors, unless one is a character vector.
a ugly workaround is this:
cell2mat(cellfun(@(x)any(ismember(x, {'a' 'c'})), output, 'UniformOutput', false))
ans =
5×1 logical array
0
1
1
1
0
but I'd rather keep my simple ismember() query. Is there a way I can modify the class/format of output, or do I need a stronger query?
Walter Roberson
Walter Roberson 2022 年 1 月 6 日
If you need to do those kinds of queries, you are better off sticking with the original representation.
mask = exampleTable.a | exampleTable.c
or even
mask = any(exampleTable{:,{'a', 'c'}},2);

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by