wolffd@0: function ndx = subv2indKPM(siz, subv) wolffd@0: % SUBV2IND Like the built-in sub2ind, but the subscripts are given as row vectors. wolffd@0: % ind = subv2ind(siz,subv) wolffd@0: % wolffd@0: % siz can be a row or column vector of size d. wolffd@0: % subv should be a collection of N row vectors of size d. wolffd@0: % ind will be of size N * 1. wolffd@0: % wolffd@0: % Example: wolffd@0: % subv = [1 1 1; wolffd@0: % 2 1 1; wolffd@0: % ... wolffd@0: % 2 2 2]; wolffd@0: % subv2ind([2 2 2], subv) returns [1 2 ... 8]' wolffd@0: % i.e., the leftmost digit toggles fastest. wolffd@0: % wolffd@0: % See also IND2SUBV. wolffd@0: wolffd@0: wolffd@0: if isempty(subv) wolffd@0: ndx = []; wolffd@0: return; wolffd@0: end wolffd@0: wolffd@0: if isempty(siz) wolffd@0: ndx = 1; wolffd@0: return; wolffd@0: end wolffd@0: wolffd@0: [ncases ndims] = size(subv); wolffd@0: wolffd@0: %if length(siz) ~= ndims wolffd@0: % error('length of subscript vector and sizes must be equal'); wolffd@0: %end wolffd@0: wolffd@0: if all(siz==2) wolffd@0: %rbits = subv(:,end:-1:1)-1; % read from right to left, convert to 0s/1s wolffd@0: %ndx = bitv2dec(rbits)+1; wolffd@0: twos = pow2(0:ndims-1); wolffd@0: ndx = ((subv-1) * twos(:)) + 1; wolffd@0: %ndx = sum((subv-1) .* twos(ones(ncases,1), :), 2) + 1; % equivalent to matrix * vector wolffd@0: %ndx = sum((subv-1) .* repmat(twos, ncases, 1), 2) + 1; % much slower than ones wolffd@0: %ndx = ndx(:)'; wolffd@0: else wolffd@0: %siz = siz(:)'; wolffd@0: cp = [1 cumprod(siz(1:end-1))]'; wolffd@0: %ndx = ones(ncases, 1); wolffd@0: %for i = 1:ndims wolffd@0: % ndx = ndx + (subv(:,i)-1)*cp(i); wolffd@0: %end wolffd@0: ndx = (subv-1)*cp + 1; wolffd@0: end wolffd@0: wolffd@0: %%%%%%%%%%% wolffd@0: wolffd@0: function d = bitv2dec(bits) wolffd@0: % BITV2DEC Convert a bit vector to a decimal integer wolffd@0: % d = butv2dec(bits) wolffd@0: % wolffd@0: % This is just like the built-in bin2dec, except the argument is a vector, not a string. wolffd@0: % If bits is an array, each row will be converted. wolffd@0: wolffd@0: [m n] = size(bits); wolffd@0: twos = pow2(n-1:-1:0); wolffd@0: d = sum(bits .* twos(ones(m,1),:),2); wolffd@0: