MATLAB: How to keep certain numbers in a cell array

cell arrayremoval

Lets say for example I have a cell array A = {1,2,3},{4,5,6},{7,8,9},{10,11,12}. I am then given the string B = [1,3,5,12]. How would I create an output cell array where the numbers which were not mentioned in the string B were removed? i.e ans = {1,3} {5} {12}
Thank you for your time
Nabil

Best Answer

A = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
B = [1,3,5,12];
R = cell(size(A));
for iA = 1:numel(A)
v = cat(2, A{iA}{:}); % A{iA} as vector

ex = ismember(v, B);
R{iA} = A{iA}(ex);
end
R = R(~cellfun('isempty', R));
Or:
R = cell(size(A));
iR = 0;
for iA = 1:numel(A)
v = cat(2, A{iA}{:}); % A{iA} as vector
ex = ismember(v, B);
if any(ex)
iR = iR + 1;
R{iR} = A{iA}(ex);
end
end
R = R(1:iR);