function [b,map] = cmpermute(a,cm,ndx)
%CMPERMUTE Move colormap positions.
%	[Y,NEWMAP] = CMPERMUTE(X,MAP) returns an image Y and associated 
%	colormap NEWMAP that produces the same image as X and MAP but
%	where the colormap has been randomly rearranged.
%
%	[Y,NEWMAP] = CMPERMUTE(X,MAP,ORDER) uses the ordering matrix from SORT
%	to define the new order.  For example to order a colormap
%	by luminance, use
%	   ntsc = rgb2ntsc(cm);
%	   [dum,order] = sort(ntsc(:,1));
%	   [b,map] = cmpermute(a,cm,order);
%
%	See also SORT.

%	Clay M. Thompson 2-19-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.8 $  $Date: 1993/09/08 16:36:42 $

error(nargchk(2,3,nargin));

n = size(cm,1);

if nargin==2, % Use random permutation
  ndx = randperm(n);
end

if length(ndx)~=size(cm,1), 
  error('The length of NDX must equal the number of rows of MAP.');
end

pos(ndx) = 1:n;

b = zeros(size(a));
b(:) = pos(a);
map = cm(ndx,:);
