Reputation: 400
Let's assume that we have a matrix like this:
A = [1 2 3 4]
how can i find the number of occurrence of this matrix in a cell like this:
B{1,1} = {1, 7, 5, 7, 1, 2 ,3 ,4 ,9 ,4 ,6 ,1 ,2 ,3 ,7}
B{1,2} = {2, 3, 4, 5, 6, 0, 5, 1, 2, 3, 4, 5, 2, 1, 0}
Is it possible to find it without loops?
Thanks in advance!
Upvotes: 0
Views: 83
Reputation: 14947
You can "abuse" strfind
, assuming you can store B1 and B2 as matrices instead of cells. You can still use a cell for the outer layer, in order to support inputs of different lengths.
% Convert storage format
C{1} = cell2mat(B{1,1});
C{2} = cell2mat(B{1,2});
indices = cellfun(@(c) strfind(c,A), C, 'UniformOutput', false);
This finds all the starting indices in each array. If you just want the total number, count the occurrences:
occurrences = cellfun(@(c) length(strfind(c,A)));
Upvotes: 1
Reputation: 183
Solution with for loops: Without for loops is possible as well but it´s a readability nightmare. I would not suggest.
numElA = numel(A);
out = zeros(size(B));
for j = 1 : numel(B) % for every cell of B
b = B{j}; % extract matrix
for i = 1 : numel(b)-numElA % for every element of b (minus the size of A)
out(j) = out(j) + all(cat(2,b{i+[0:numElA-1]})==A); % compare the two vectors (indexed b and a). If they are the same count them +1
end
end
update: this is the version without for loops
indA = 1:numel(A);
indB = cellfun(@(x) num2cell(bsxfun(@plus,(1:numel(x)-max(indA))',indA-1),2),B,'uniformoutput',false);
out = cellfun(@sum,cellfun(@(MAT,IND) cellfun(@(ind) all(cat(2,MAT{ind})==A),IND),B,indB,'UniformOutput', false));
Upvotes: 2