简体   繁体   English

在单元格数组(Matlab)中查找字符串的行索引

[英]Find row Index of strings in cell Array (Matlab)

If I have a cell array C : 如果我有一个单元格数组C

C =  {'name'  'hh' '23' []     []
    'last'  'bb' '12' '8'    'hello'
    'In'    'kk' '12' '2131' []
    'name'  'kk' '23' []     []
    'name'  'cv' '22' []     []
    'name'  'ph' '23' []     [] } ;

How can I get the row index of all the rows that have 'name' in the first column and '23' in the third column? 如何获得第一列中具有“名称”和第三列中具有“ 23”的所有行的行索引?

indexresult = [1,4,6] 

The simplest way to do this (all-versions compatible) would be to just use strcmp , which can accept cell arrays and does a "string compare". 最简单的方法 (兼容所有版本)是使用strcmp ,它可以接受单元格数组并执行“字符串比较”。

One liner 一支班轮

indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'));
% indexresult = [1; 4; 6];

Explanation 说明

% Get logical array of rows where first column is 'name'
logicalname = strcmp(C(:,1), 'name');
% Get logical array of rows where third column is '23'
logical23 = strcmp(C(:,3), '23');
% Get logical array where both of the above are true, using and (&)
logicalname23 = strcmp(C(:,1), 'name') & strcmp(C(:,3), '23');
% Get indices from logical array using find
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'));
% If you wanted a row vector instead of column vector, just transpose too
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23')).';

If you want to be case insensitive (matching 'name', 'NAME', 'Name', ... ) then use strcmpi instead of strcmp . 如果您不区分大小写(匹配'name', 'NAME', 'Name', ... ),请使用strcmpi而不是strcmp

YOu can use strfind to get the indices which has string name and then use logical indices to get 23 out of the obtained indices. 您可以使用strfind获取具有字符串名称的索引,然后使用逻辑索引从所获取的索引中获取23个。

C =  {'name'  'hh' '23' []     []
   'last'  'bb' '12' '8'    'hello'
   'In'    'kk' '12' '2131' []
   'name'  'kk' '23' []     []
   'name'  'cv' '22' []     []
   'name'  'ph' '23' []     [] } ;

% find indices of name
idx = strfind(C(:,1), 'name');
idx = find(not(cellfun('isempty', idx)));
% pick 23 from 3rc column

iwant =idx((str2double(C(idx,3))==23))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM