Kola
Kola

Reputation: 77

Comparing content of a cell array with a vector

I have the following 1-by-3 cell arrays:

Y = {[2 3 4 5 8],[1 2 5 7 8],[3 4 7 8]}

and the following 1-by-8 vector:

X = [1 2 3 4 5 6 7 8]

Using a form of logical index, I will like to compare the vector with each content of the cell array. For instance, comparing X with Y(1,1) would give the following:

[0 1 1 1 1 0 0 1]

likewise, comparing X with Y(1,2) will give the following:

[1 1 0 0 1 0 1 1]

And comparing X with Y(1,3) will give the following:

[0 0 1 1 0 0 1 1]

Hence, I should have the following output:

[0 1 1 1 1 0 0 1
 1 1 0 0 1 0 1 1
 0 0 1 1 0 0 1 1]

Grateful for any form of help.

Upvotes: 1

Views: 38

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Use cellfun to apply ismember to each cell's contents:

result = cellfun(@(c) ismember(X, c), Y, 'UniformOutput', false); % gives cell array
result = vertcat(result{:}); % vertically concatenate cells' contents into a matrix

Upvotes: 3

Related Questions