Daniel@0: function sub = ind2subvKPM(siz, ndx) Daniel@0: % IND2SUBV Like the built-in ind2sub, but returns the answer as a row vector. Daniel@0: % sub = ind2subv(siz, ndx) Daniel@0: % Daniel@0: % siz and ndx can be row or column vectors. Daniel@0: % sub will be of size length(ndx) * length(siz). Daniel@0: % Daniel@0: % Example Daniel@0: % ind2subv([2 2 2], 1:8) returns Daniel@0: % [1 1 1 Daniel@0: % 2 1 1 Daniel@0: % ... Daniel@0: % 2 2 2] Daniel@0: % That is, the leftmost digit toggle fastest. Daniel@0: % Daniel@0: % See also SUBV2IND Daniel@0: Daniel@0: n = length(siz); Daniel@0: Daniel@0: Daniel@0: if n==0 Daniel@0: sub = ndx; Daniel@0: return; Daniel@0: end Daniel@0: Daniel@0: if all(siz==2) Daniel@0: sub = dec2bitv(ndx-1, n); Daniel@0: sub = sub(:,n:-1:1)+1; Daniel@0: return; Daniel@0: end Daniel@0: Daniel@0: cp = [1 cumprod(siz(:)')]; Daniel@0: ndx = ndx(:) - 1; Daniel@0: sub = zeros(length(ndx), n); Daniel@0: for i = n:-1:1 % i'th digit Daniel@0: sub(:,i) = floor(ndx/cp(i))+1; Daniel@0: ndx = rem(ndx,cp(i)); Daniel@0: end Daniel@0: Daniel@0: Daniel@0: Daniel@0: %%%%%%%%%% Daniel@0: Daniel@0: function bits = dec2bitv(d,n) Daniel@0: % DEC2BITV Convert a decimal integer to a bit vector. Daniel@0: % bits = dec2bitv(d,n) is just like the built-in dec2bin, except the answer is a vector, not a string. Daniel@0: % n is an optional minimum length on the bit vector. Daniel@0: % If d is a vector, each row of the output array will be a bit vector. Daniel@0: Daniel@0: Daniel@0: if (nargin<2) Daniel@0: n=1; % Need at least one digit even for 0. Daniel@0: end Daniel@0: d = d(:); Daniel@0: Daniel@0: [f,e]=log2(max(d)); % How many digits do we need to represent the numbers? Daniel@0: bits=rem(floor(d*pow2(1-max(n,e):0)),2);