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