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
B =
n×1 cell array
I want a output matrix of whether patterns in A has appear 7 times in B:
C =
m×1 logical array
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);
Any way to vectorize the code?


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) = ...
  4 件のコメント
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;
which is basically the code you had originally.


その他の回答 (0 件)


Find more on Loops and Conditional Statements in Help Center and File Exchange





Community Treasure Hunt

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

Start Hunting!

Translated by