【问题标题】:Matlab - Find index of a cell by its valueMatlab - 通过其值查找单元格的索引
【发布时间】:2014-11-03 17:44:02
【问题描述】:

我有一个单元格数组 filedNames 11x1,其中每个单元格都是一个字符串,我想获取等于字符串名称的单元格的索引。

我找到了这个例子:

C = { {'a'}, {'b'}, {'c'}, {'a'}, {'a'} } % data
idx = find(strcmp([C{:}], 'a')) % single line engine

但是,当我将其应用于我的案例时:

find(strcmp([fieldNames{:}], 'b_h_epsQ_h'))

什么都没有发生,并且 strcmp([fieldNames{:}], 'b_h_epsQ_h') 本身没有找到匹配项,尽管如果我输入 strcmp([fieldNames{2}], 'b_h_epsQ_h') 答案是 1。

我绑定了以 1x5 为例的单元格数组转置仍然没有成功

【问题讨论】:

  • 该示例是一个包含元胞数组(嵌套)的元胞数组。你的只是一个字符串的单元格数组。所以试试:strcmp(fieldNames, 'b_h_epsQ_h')

标签: string matlab strcmp cell-array


【解决方案1】:

使用以下内容:

idx = strcmp(fieldNames, 'b_h_epsQ_h')
find(idx)

示例:

>> fieldNames = {'a', 'b', 'c', 'd', 'e'};
>> idx = strcmp(fieldNames, 'c')
idx =
     0     0     1     0     0
>> find(idx)
ans =
     3

【讨论】:

    【解决方案2】:

    试试这个:

    index = zeros(1,length(fieldNames))
    for i = i:length(fieldNames)
        if find(strcmp([fieldNames{:}], 'b_h_epsQ_h')) == 1
            index[i] = 1
        end
    end
    

    如果您想在找到匹配的字符串后立即退出,请在 'index = i' 之后的 'if' 子句中添加一个 'break'。

    【讨论】:

      【解决方案3】:

      你也可以试试:

      idx = cellfun(@(x)strcmp(x,'c'), C);
      

      【讨论】:

        猜你喜欢
        • 2012-11-11
        • 1970-01-01
        • 2014-02-16
        • 2012-03-03
        • 2020-04-20
        • 2013-08-06
        • 2017-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多