Convert Matlab colormap to Surfer colormap

In the comment section of my last post, Steve asked if I had code to generate a Surfer.clr file from my Matlab colormaps.

Some time ago I did write a simple Matlab .m file to write a colormap to a variable with the correct Surfer format, but at the time I was content to have the variable output to a .txt file, which I would then open in a text editor to add a 1-line header and change the file extension to .clr.

I went back, cleaned up the script, and automated all the formatting. This is my revised code (you may need to change the target directory c:\My Documents\MATLAB):

%% Make a Matlab colormap
% one of the colormaps from my function, Perceptually improved colormaps
sawtooth=pmkmp(256,'swtth');
%% Initialize variable for Surfer colormap
%reduce to 101 samples
sawtooth_surfer=zeros(101,5);
%% Make Surfer colormap
% add R,G,B columnns
for i=1:3 
sawtooth_surfer(:,i+1)=round(interp1([1:1:256]',sawtooth(:,i),(linspace(1,256,101))')*255);
end
% add counter and alpha (opacity) columns
sawtooth_surfer(:,1)=linspace(0,100,101);
sawtooth_surfer(:,5)=ones(101,1)*255;
%% Create output file 
filename='c:\My Documents\MATLAB\stth4surf.clr'; 
fileID=fopen(filename,'wt');
%%  Write Surfer colormap header
fprintf(fileID,'ColorMap 2 1\n');
fclose(fileID);
 
%% Add the colormap:
dlmwrite('c:\My Documents\MATLAB\stth4surf.clr',...
    sawtooth_surfer,'precision',5,'delimiter','\t', '-append');