Prev: filter design in matlab
Next: moving average
From: Kevin Kleine on 16 Apr 2010 11:44 Does anyone know how I can use a vector V, for instance V = [3 2], as an index for a multidimensional array M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ], so that M(function(V)) = 8 ????
From: Matt Fig on 16 Apr 2010 11:55 Have a look at SUB2IND.
From: Yi Cao on 16 Apr 2010 11:57 "Kevin Kleine" <kikleine(a)gmail.com> wrote in message <hqa0k5$i5c$1(a)fred.mathworks.com>... > Does anyone know how I can use a vector V, for instance V = [3 2], as an index for a multidimensional array M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ], so that M(function(V)) = 8 ???? One way to do it is convert the vector V to a linear index, n = size(M,1); f = V(1) + (V(2)-1)*n; M(f) %should be 8 HTH Yi
From: Kevin Kleine on 16 Apr 2010 13:20 thanks for the quick reply, however: I don't know in advance the size or number of dimensions of the matrix. It might just as well be a 6-dimensional matrix. To use sub2ind, or your method, the matrix has to have a fixed size, or am I mistaken?
From: Matt Fig on 16 Apr 2010 13:44
SUB2ind takes the size of the array as an input argument. If V may have the same number of elements as M has dimensions, use comma-separated list syntax by using NUM2CELL on V. For example: % Randomly dimensioned data M = rand(cellfun(@(x) ceil(rand*2)+4,cell(1,ceil(rand*8)))); V = ceil(rand(1,ndims(M))*3) % Index into M. Vc = num2cell(V) M(sub2ind(size(M),Vc{:})) |