[英]Find row Index of strings in cell Array (Matlab)
如果我有一個單元格數組C
:
C = {'name' 'hh' '23' [] []
'last' 'bb' '12' '8' 'hello'
'In' 'kk' '12' '2131' []
'name' 'kk' '23' [] []
'name' 'cv' '22' [] []
'name' 'ph' '23' [] [] } ;
如何獲得第一列中具有“名稱”和第三列中具有“ 23”的所有行的行索引?
indexresult = [1,4,6]
最簡單的方法 (兼容所有版本)是使用strcmp
,它可以接受單元格數組並執行“字符串比較”。
一支班輪
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'));
% indexresult = [1; 4; 6];
說明
% 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')).';
如果您不區分大小寫(匹配'name', 'NAME', 'Name', ...
),請使用strcmpi
而不是strcmp
。
您可以使用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.