Comparing a cell with a vector in Matlab

62 views Asked by At

I have a cell A in Matlab of dimension 1x3, e.g.

A={{1,2,3,4} {5,6} {7,8,9} }

A contains all the integers from 1 to n in increasing order. In the example n=9. However, the number of elements within each sub-cell can be different. Each sub-cell is non-empty.

Consider the vector B of dimension nx1 containing some integers from 1 to n in increasing order (repetitions are allowed), e.g.

B=[1 1 2 2 4 7 7 8 9]'

I want to construct (without using loops) the vector C of dimension nx1 such that each C(i) tells which sub-cell of A B(i) belongs to. In the example

C=[1 1 1 1 1 3 3 3 3]'
2

There are 2 answers

0
Luis Mendo On BEST ANSWER

With that structure, A is uniquely determined by the number of elements of each of its cells, and the result can be obtained as

C = sum(bsxfun(@gt, B, cumsum(cellfun(@numel, A))), 2)+1;
0
zeeMonkeez On

I don't know whether it's faster than for loops, but how about

C = arrayfun(@(b) find(cellfun(@(a) any(cell2mat(a) == b), A)), B);

Explanation: pick each element b in B; then pick every sub-cell a in A and check for equality with b, return the index of sub-cell b is a member of.