フィルターのクリア

find multiple words in a cell

2 ビュー (過去 30 日間)
Vincent I
Vincent I 2013 年 1 月 9 日
Hi, is there a way to compare and return a number for the matching words in two unequal cells?
A={'a','a','a','b','b','d'} B={'a','b','c','d','e','f','g','h'}
return C=3,2,0,1,0,0,0,0
Thank you

採用された回答

Ryan Livingston
Ryan Livingston 2013 年 1 月 9 日
A one-liner:
cellfun(@(x)sum(ismember(A,x)), B)
  1 件のコメント
Vincent I
Vincent I 2013 年 1 月 9 日
Fantastic, thank you . thats what I was looking for

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

その他の回答 (3 件)

Matt J
Matt J 2013 年 1 月 9 日
If the "words" will really always be single letters, you could do it looplessly with
>> histc([A{:}], [B{:}])
ans =
3 2 0 1 0 0 0 0
  6 件のコメント
Matt J
Matt J 2013 年 1 月 9 日
編集済み: Matt J 2013 年 1 月 9 日
And, although this is a new question, I feel that it is not far away for the initial question which I dont see why should require a new post
It doesn't require it, but if you post it as a new question, people have the opportunity to gain points from answering you (now that you've already accepted Ryan's answer), and so will be more incentivized to do so.
Jan
Jan 2013 年 1 月 10 日
編集済み: Jan 2013 年 1 月 10 日
The decision is easy:
New question, new thread.
And:
Additional information to an existing question is added by editing the question and marking the changes by "[EDITED]". Then this is clarification and *not* a new question.
Hiding important information in deeply nested comments to already accepted questions is a bad idea.

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


Daniel Shub
Daniel Shub 2013 年 1 月 9 日
I am sure that this is over thinking the solution and I doubt that using regexp is optimal, but I was curious how bad it would be.
x = regexp(A, cell2mat(cellfun(@(x)['(?<', x, '>', x, ')|'], B, 'UniformOutput', false)), 'names');
cellfun(@(x)length([y.(x)]), fieldnames([x{:}]))'
I is there a better way to do this with regexp?
  1 件のコメント
Vincent I
Vincent I 2013 年 1 月 9 日
編集済み: Vincent I 2013 年 1 月 9 日
Solved my problem by doing the folowing:
A=TF(:,1).';
A=regexprep(A, ' ','');
A=regexprep(A, '_(\w*)','');
B={'aa','bb2c','bb25c','xy3c','m56c','etc56c'};
C=cellfun(@(x)sum(strcmp(A, x)), B);
Thank you

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


Jan
Jan 2013 年 1 月 10 日
[EDITED, Jan, moved from comments to the accepted question]
ISMEMBER sorts the inputs and performs a binary search. This can be much faster and much slower than an unsorted comparison by:
cellfun(@(x)sum(strcmp(A, x)), B)
I claim without a proof, that a loop is faster:
R = zeros(1, numel(B));
for iB = 1:numel(B)
R(iB) = sum(strcmp(A, B{iB}));
end
[EDITED 2] And if you want to compare the leading character(s) only:
...
R(iB) = sum(strncmp(A, B{iB}, length(B{iB}));
...
  1 件のコメント
Vincent I
Vincent I 2013 年 1 月 10 日
sounds goood. Thanks for your answer

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

カテゴリ

Help Center および File ExchangeDebugging and Analysis についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by