function s=sample(A,m,r)

% SAMPLE      Random sampling of points from a data-set.
%
%             SAMPLE(A,M,R) selects a random sample of M data points from the
%             multivariate data-set in the matrix A.
%             If R<>0 the sampling is performed with replacement.

if nargin~=3,
  error('Incorrect number of function parameters');
end;	

[n d]=size(A);

if m>n & r==0,
  error('Requested sample size too large');
end;

if m==n & r==0,
  s=A;
  return;
end;
		
counter=0;

if r==0, % Sample without replacement.
  while counter<m,
    counter=counter+1;
    found=0;
	  while found==0, % Keep looping until a new index is found.
	    index(counter)=ceil(n*rand); % Random integer between 1 and n.
	    if counter>1,
		    found=1; 
  		  for i=1:length(index)-1, % Loop around previous values. 
	  	    if index(i)==index(counter), % Check if index has been used already.
		  	    found=0;
			    end;
  		  end;
	  		else, % If counter=1.
		  	  found=1;
  	  end;		
	  end;			
  end;
  else, % Sample with replacement.
	  index=ceil(n*rand(m,1));
end;

s=A(index,:);