【问题标题】:Select rows from a table based on conditions in two columns根据两列中的条件从表中选择行
【发布时间】:2018-03-01 14:33:24
【问题描述】:

假设我们有下表mytable

                     Name                            id         Factor       Correct
    ___________________________________________    ________    _________    ____________

    'Maria'                                        '7324'      'x'           'Yes'      
    'Lina'                                         '7827'      'x'           'Yes'      
    'Jack'                                         '7831'      ''            'No'      
    'Van'                                          '7842a'     'x'           'No'      
    'Julia'                                        '7842c'     ''            'Yes'   

我想从 mytable 中选择所有行,其中 Factor = 'x' AND Correct = 'Yes' 并将它们分配到一个新表中。对于每一列的类(例如,'Name' 列),我们有:

class(mytable.Name) = cell

我试过这段代码:

newtable = mytable((mytable.Correct == 'Yes') & (mytable.Factor == 'x'))

得到了错误:

Undefined operator '==' for input arguments of type 'cell'

我尝试了第二种方法:

newtable = mytable((cell2mat(mytable.Correct) == 'Yes') & (cell2mat(mytable.Factor) == 'x'))

这次又报错了:

Error using cat
Dimensions of matrices being concatenated are not consistent.

这是有道理的,因为与“否”相比,“是”的大小不同。我正在考虑用“Y”和“N”重新分配“正确”列。然而,这并不是我真正想要的。有什么建议吗?

【问题讨论】:

    标签: matlab matlab-table


    【解决方案1】:

    由于您的表格在每个单元格中都包含字符数组,您可以与strcmp 进行比较以提取所需的行:

    newtable = mytable(strcmp(mytable.Correct, 'Yes') & strcmp(mytable.Factor, 'x'), :);
    

    产生以下结果:

    newtable = 
    
         Name        id      Factor    Correct
        _______    ______    ______    _______
    
        'Maria'    '7324'    'x'       'Yes'  
        'Lina'     '7827'    'x'       'Yes'  
    

    注意,我使用比较的结果作为行索引,然后使用: 作为列索引来选择所有列。您可以阅读this documentation,了解有关访问表中数据的不同方式的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-09
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      相关资源
      最近更新 更多