
Re: logical index in multidimensional arrary
Posted:
Sep 16, 2013 4:37 AM


"jay cao" <eijoac@hotmail.com> wrote in message news:l11tcb$67p$1@newscl01ah.mathworks.com... > Hi all, > > The following doesn't work. Why is it? > > test = ones(2, 3, 2) > idx = [1, 0, 1; 0, 1, 0] > idx = logical(idx) > test(idx, 1) > > the error from the last command is "Index exceeds matrix dimensions." It > works if test is a 2d array, i.e., the following works. > > test = ones(2, 3) > idx = [1, 0, 1; 0, 1, 0] > idx = logical(idx) > test(idx) > > why doesn't the logical index work in high dimensional array as in 2d > array? How can I get around with it, say i want to assign some values to > test(idx, 1) where idx is a logical index 22 array. > > Thanks. > > Jay
test holds 12 values in a 2x3x2 array. idx holds 6 values.
When you index into test as test(idx,1) you are saying you want 6 row values and are combining columns and pages in the 2nd index. To MATLAB, it is trying to index into test as if test's size was 6x prod(3*2). But really, as a 2d view, test's size is 2by 6  not 6x6.
MATLAB will only collapse trailing dimensions for the purposes of indexing, not the leading ones. You can, however, collapse to a single dimension  which is why your 2d case works.
 Loren
http://blogs.mathworks.com/loren

