Search code examples
arraysmatlabcell-array

Comparing a cell with a vector in Matlab


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]'

Solution

  • 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;