It is very important to know the powerful yet very intuitive feature of the matrix indexing in Matlab. So how indexing actually works and what is the valid index would help avoid above error in a first place by using the valid indices.
At its very core, given the array A of length n, there are two ways to index it.
1. Linear indexing: With a subset of integers from 1 : n ,0 is not allowed, as the Matlab arrays are 1-based, unless you use a method below. For a higher-dimensional arrays, multiple subscripts are the internally converted into a linear index, although in the efficient and transparent manner.
2. Logical indexing: When you use the n-length array of 0s and 1s, to just pick those elements where the indexing is true. In this case, the unique(index) must have only 0 and 1.
So the valid indexing array into another array with the n number of elements can be:
1. Entirely logical of a same size, or
2. Linear with a subsets of integers from 1:n
So invalid indexing error always occurs when you try to mix the two types of indexing: one or more zeros occur in the linearly indexing array, or you just mix 0s and 1s with anything other than 0s and 1s.