find indices of string matches from a cell array by thier endings

I want to find the indices of a cell array whose memembers end with a specific string. Eg.
A={'aAbc' 'dgbc' 'bebd' 'fabc' 'fa '}
Now if I want to find out the indices of the strings which end either with two characters'bc' or ' ' (empty), which command in Matlab would be suitable for this ?

 採用された回答

Chad Greene
Chad Greene 2014 年 3 月 20 日
編集済み: Chad Greene 2014 年 3 月 20 日

4 投票

Do it without loops to make it a bit faster:
A={'aAbc' 'dgbc' 'bebd' 'fabc' 'fa ' 'abcd' 'abcdkads' 'a' 'snacks bc'};
myindices = ~cellfun(@isempty,regexp(A,'bc$'))

4 件のコメント

Dishant Arora
Dishant Arora 2014 年 3 月 20 日
It makes me feel stupid. +1
Chad Greene
Chad Greene 2014 年 3 月 20 日
I just saw the bit about "or ends in empty". Here's a fix:
myindices = ~cellfun(@isempty,regexp(A,'bc$')) + ~cellfun(@isempty,regexp(A,' $'))
Meh
Meh 2014 年 3 月 21 日
Thanks. It works. May I ask you what is the task of @isempty in the code?
Chad Greene
Chad Greene 2014 年 3 月 21 日
If regexp(A,'bc$') were an array of numbers, you could put it inside a function like isempty(regexp(A,'bc$')). However, regexp(A,'bc$') is not an array of numbers, it's an array of cells. You can operate on cells as if they were numbers if you use cellfun(@FUNCTION,...), hence, cellfun(@isempty,regexp(A,'bc$')).

サインインしてコメントする。

その他の回答 (3 件)

Jos (10584)
Jos (10584) 2014 年 3 月 21 日

3 投票

You can use REGEXP to find a specific string property. Moreover you can combine various properties using the separator |
A={'aAbc' 'dgbc' 'bebd' 'fabc' 'fa '}
indexA = find(~cellfun(@isempty, regexp(A,'bc$| $')))

1 件のコメント

Chad Greene
Chad Greene 2014 年 3 月 21 日
Ah, good thinking. I knew there'd be a way to include the or operator in regexp.

サインインしてコメントする。

Sara
Sara 2014 年 3 月 20 日

0 投票

strcmp or strcmpi
Example of how you could do it (not elegant but works):
A={'aAbc' 'dgbc' 'bebd' 'fabc' 'fa '};
str = 'bc';
index = zeros(length(A),1);
str_length = length(str);
for i = 1:length(A)
k1 = strcmp(A{i}(end-str_length+1:end),str);
k2 = strcmp(A{i}(end-str_length+1:end),blanks(str_length));
if(k1 ~= 0 || k2 ~= 0)
index(i) = i;
end
end
index = index(index>0);
Dishant Arora
Dishant Arora 2014 年 3 月 20 日

0 投票

A = {'aAbc' 'dgbc' 'bebd' 'fabc' 'fa '};
fun = @(x) (length(x) == regexp(x , 'bc' , 'end'))
B = cellfun(fun,A,'Un',0);
for ii=1:length(B)
if isempty(B{ii})
B{ii} = false;
end
end
Idx = A(cell2mat(B))
There might be better ways to do it, but this is what I come up with.

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

製品

質問済み:

Meh
2014 年 3 月 20 日

コメント済み:

2014 年 3 月 21 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by