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