Check appearance counts of multiple patters in a cell matrix

조회 수: 1 (최근 30일)
Yi-xiao Liu
Yi-xiao Liu 2020년 1월 8일
댓글: Guillaume 2020년 1월 9일
I have 2 cell matrixs:
A =
m×1 cell array
{'abc'}
{'def'}
{'123'}
......
B =
n×1 cell array
{'abcsafadefs2'}
{'dsabcdsdef11'}
{'abcssp123'}
......
I want a output matrix of whether patterns in A has appear 7 times in B:
C =
m×1 logical array
{true}
{true}
{false}
......
So in this example pattern "abc" have matches in exactaly 7 elements in B, so does "def", but not "123".
I now do this with a for loop
for i=1:length(A)
C(i)= (nnz(contains({B}, A(i)))==7);
end
Any way to vectorize the code?

채택된 답변

Guillaume
Guillaume 2020년 1월 8일
Any way to vectorize the code?
Not really, you could cellfun it, but that's not vectorisation (cellfun is just a loop in disguise):
C = cellfun(@(a) nnz(contains(B, a)) == 7, A);
Note that if you use a loop, you should preallocate the output:
C = false(size(A));
for i = 1:numel(A)
C(i) = ...
end
  댓글 수: 4
Yi-xiao Liu
Yi-xiao Liu 2020년 1월 8일
편집: Yi-xiao Liu 2020년 1월 8일
Can you explain more on the example? I find myself having hard time understanding it, though it does work
Guillaume
Guillaume 2020년 1월 9일
cellfun(fun, A) applies the function fun to each element of A. Here, fun is the anonymous function:
@(a) nnz(contains(B, a)) == 7
which written as normal function would be equivalent to:
function out = anonymous_function(a)
%unlike normal functions, anonymous functions can capture variables in the enclosing function
%so B is in scope in the anonymous function
out = nnz(contains(B, a)) == 7;
end
which is basically the code you had originally.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by