0

I have a 1x234 cell array called tmp from which I want to delete all duplicates. Some elements of tmp can be:

tmp{1, 3} -> 'Ro'
tmp{1, 167}{1, 1} -> 'Ro'
tmp{1, 167}{1, 2} -> 'CvF'

Of the first two, I'd like to keep just tmp{1, 167}{1, 1} -> 'Ro'.

Also, I would like to turn entries that contain cells-within-cells, such as:

tmp{1, 167}{1, 1} -> 'Ro'
tmp{1, 167}{1, 2} -> 'CvF'

Into:

tmp{1, 167}-> 'Ro'
tmp{1, 168}-> 'CvF'

How can I achieve these two goals?

2
  • It is possible, yes. However, the exact implementation depends on the structure of your data, and specifically how deeply nested it is, does it consist only of cells, etc. It also depends on how efficient your solution needs to be. If all your data are character vectors nested in cells of unknown depth, you could create a string vector and iteratively+recursively "unbox" your cell arrays and assign entries to this one vector. Once your data structure is flattened, removing duplicates is trivial (using unique). Commented Feb 16, 2021 at 10:00
  • thank you for your answer. Its quite hard to understand what you mean. Its not deeply nested. The deepest level is the one I posted earlier. tmp{1, 167}{1, 1} -> 'Ro' tmp{1, 167}{1, 2} -> 'CvF' The contents of the array are only letters. Commented Feb 16, 2021 at 11:48

1 Answer 1

1

TL;DR: unq = unique([tmp{:}]);


If your maximum nesting level is 2 (i.e. cell in a cell), flattening the array does not require any sort of recursive functions, and can be achieved using a simple concatenation. See complete example below:

function unq = q66221704()
%% Generate some data:
rng(66221704); % for reproducibility
N = 2;
tmp = cell(1,234);
for k = 1:numel(tmp)
  if rand(1) < 0.6 % create nested cells with some probability
    tmp{k} = getLowercaseString(N);
  else
    tmp{k} = {getLowercaseString(N), getLowercaseString(N)};
  end
end

%% Flatten cell array:
new = [tmp{:}]; % size = 1x352

%% Keep uniques:
unq = unique(new); % size = 1x259
end

function c = getLowercaseString(nChars)
c = char(randi([97, 122], [1, nChars]));
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.