function dispmtx(M,varargin)
% Show the contents of a matrix in a nicely formatted way with headers.
%
% USAGE: dispmtx(M[,fmt][,colsize],[colhead{:}],[rowread{:}])
%
% Example: dispmtx(randn(3,2),{'col1' 'col2'},{'row1' 'row2' 'row3'})
%
%
%
% Aslak Grinsted apr2004
varargin{6}=[]; %---so that i don't have to check on length all the time.
if ischar(varargin{1})&&(size(varargin{1},1)==1)
fmt=varargin{1};
varargin(1)=[];
else
%----autofmt----
sp=max(floor(2.5-log10(nanstd(M(:)))),0);
mx=max(ceil(log10(nanmax(abs(M(:))))),1)+any(M(:)<0);
fmt=sprintf('%%%i.%if',mx,sp);
end
if isnumeric(varargin{1})&&(numel(varargin{1})==1)
lc=varargin{1}; %length of column
varargin(1)=[];
else
lc=length(sprintf(fmt,max(abs(M(:)))))+1+any(M(:)<0); %determine lc by length of FMT
end
rowhead=strvcat(varargin{2}); %#ok
rowheadwidth=size(rowhead,2)+1;
rowheadspaces=[zeros(1,rowheadwidth)+32 ''];
colhead=varargin{1};
if ~isempty(colhead)
colhead=strvcat(colhead); %#ok
if (size(colhead,2)>=lc)
colhead=colhead(:,1:(lc-1)); %truncate
end
colhead=cellstr(colhead);
disp([rowheadspaces sprintf(['%' num2str(lc) 's'],colhead{:})]);
end
colwidth=ones(1,size(M,2))*lc;
colidx=cumsum(colwidth)+rowheadwidth-lc;
for ii=1:size(M,1)
srow=[zeros(1,colidx(end)+lc)+32 '']; %spaced string
if ii<=size(rowhead,1)
srow(1:size(rowhead,2))=rowhead(ii,:);
end
for jj=1:size(M,2)
if ~isnan(M(ii,jj))
s=sprintf(fmt,M(ii,jj));
else
s='';
end
if length(s)>=lc
s=[s(1:(lc-2)) '?'];
end
s=sprintf(['%' num2str(lc) 's'],s);
srow(1,colidx(jj)+(1:lc))=s;
end
disp(srow)
end