myrandint.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. function ranInt = myrandint(outputRow,outputCol,outputRange,varargin)
  2. % MYRANDINT(M,N,RANGE) is an M-by-N matrix with random integer entries
  3. % drawn with replacement from elements of vector RANGE. The elements in
  4. % vector RANGE do not need to be contiguous or unique. (Actually, they do
  5. % not even need to be integers: The function works the exact same way with
  6. % noninteger elements, but a warning is generated to alert the user that
  7. % noninteger elements are being sampled.)
  8. %
  9. % To specify a contiguous integer range from Xlow to Xhi, use RANGE = [Xlow:Xhi].
  10. %
  11. % MYRANDINT(M,N,RANGE,'noreplace') is an M-by-N matrix with random integers
  12. % drawn without replacement.
  13. %
  14. % This function is based around RAND and RANDPERM, and is intended as a
  15. % modest imitation of Comm Toolbox's RANDINT.
  16. if isequal(size(outputRange),[1 2]) && ~isequal(outputRange(1),outputRange(2)-1),
  17. warning('To specify a range [low high] use [low:high].')
  18. end
  19. if ~isequal(round(outputRange),outputRange),
  20. warning('Specified RANGE contains noninteger values.')
  21. end
  22. if ~isequal(length(outputRange),length(outputRange(:))),
  23. error('Range must be a vector of integer values.')
  24. end
  25. numElements = outputRow*outputCol;
  26. if isempty(varargin),
  27. ranInt = zeros(outputRow,outputCol);
  28. randIx = floor((length(outputRange))*rand(size(ranInt))) + 1;
  29. ranInt = outputRange(randIx);
  30. if ~isequal(size(randIx),size(ranInt)),
  31. ranInt = reshape(ranInt,size(randIx));
  32. end
  33. elseif isequal(varargin{1},'noreplace'),
  34. if numElements > length(outputRange),
  35. error('Not enough elements in range to sample without replacement.')
  36. else
  37. % Generate full range of integers
  38. XfullShuffle = outputRange(randperm(length(outputRange)));
  39. % Select the first bunch:
  40. ranInt = reshape(XfullShuffle(1:numElements),outputRow,outputCol);
  41. end
  42. else
  43. error('Valid argument is ''noreplace''.')
  44. end