from samplepick by Mauro
pick a random sample out of an array

samplepick(x,n,dim)
function [y,IX] = samplepick(x,n,dim)

% [y,IX] = samplepick(x,n,dim)
%
% The function 'y = samplepick(x,n)' choose random lines (samples) of size n out of the array x.
% [~,IX]  = samplepick(x,n) ist the vector of random samples --> y = x(IX(1:n),:)
%           You can use IX to pick multible samples from x
%           IX contain numbers from 1 to n in a random order.
%           Example 2x samles of size 5 from x (not puting back!)
%               S1 = x(IX(1:5),:);
%               S2 = x(IX(6:10),:);
%               ...
%
% [y,IX] = samplepick(x,n,dim) dim 1 is for row-wise, dim = 2 is col-wise
% Example:
%     n_dim = 20;
%     rand('seed',200)
%     x = [(1:n_dim)',round(rand(n_dim,1)*10)];
% 
%     sample_size = 5;
% 
%     [y, IX] = samplepick(x,sample_size,1);

if nargin <3, dim=1;end
if isscalar(n)==0,error('Input sample size is not numeric'),end
if ~(dim==1 || dim==2),error('dim must be 1 or 2'),end

% size of all sample
n_x = size(x,dim);

switch dim
    case 1
        if n_x<=n,error('sample size bigger then X'),end
        IX = randperm(n_x);
        y = x(IX(1:n),:);
    case 2
        n_x = size(x,dim);
        if n_x<=n,error('sample size bigger then X'),end
        IX = randperm(n_x);
        y = x(:,IX(1:n));
        IX = IX';
    otherwise
        y = x;
        IX=[];
end

Contact us at files@mathworks.com