2017-07-28 9 views
0

私はセルアレイCしている場合:私は最初に「名前」を持っているすべての行の行インデックスを取得できますか検索行インデックス(Matlabの)

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

を第3列の'23'

indexresult = [1,4,6] 

答えて

4

この(互換性のあるすべてのバージョン)を行う最も簡単な方法は、単にセル配列を受け入れることができ、「文字列が比較」ん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', ...に一致する)大文字と小文字を区別したい場合は、代わりにstrcmpstrcmpiを使用しています。

-1

あなたは、文字列名を持つインデックスを取得し、取得した指標のうち、23を取得するために論理的なインデックスを使用するようにstrfindを使用することができます。

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)) 
+2

'strfindは' 'name1234 'のように' '' name ''を含む文字列にもマッチすることに注意してください – Wolfie

関連する問題