function [hd,bdy] = nma_format_matrix(headings,data,wid,fms,fid,flag) %prints matrix of numerical data with headings in formatted way % nma_format_matrix() % % prints matrix of numerical data with headings in formatted way % % INPUT: % headings: a cell array of strings for the headings of each column % data: a matrix, contains the numerical data % wid: how wide a field to use (see below for example) % fms: the formating cell string array to use for the numerical data % each string corresponds to formatting a field in the numberical % data % fid: the file id to print to. Use 1 for stdout % flag: if 0, then will not print anything, just format and return % result % % Examples calling % % titles={'number of projects','sales','profit'}; % data=[2 rand(1) rand(1); % 3 rand(1) rand(1)]; % % Suppose we want to format each numerical number above as %16.5E, then % in this case 10 will be the field width, and '.5E' is what to use for % the fms argument % % wid = 16; % fms = {'d','.4E','.5E'}; % fileID = 1; % nma_format_matrix(titles,data,wid,fms,fileID,false); % % version 1.0 10/15/2010 % All blame to Nasser M. Abbasi % Thanks for help from matlab newsgroup: Ross W, Bruno Luong % % % do some basic checking on input % if nargin ~= 6 error 'number of arguments must be 6' end if ~iscell(headings) error 'headings must be cell array' end if ~iscell(fms) error 'fms must be cell array' end if isempty(headings) error 'headings can not be empty'; end if isempty(data) error 'data can not be empty'; end if isempty(fms) error 'fms can not be empty'; end [nRowH,nColH] = size(headings); if(nRowH>1) error 'headings can not have more than one row'; end [nRowFms,nColFms] = size(fms); if(nRowFms>1) error 'fms can not have more than one row'; end if(nColH ~= nColFms) error 'headings must have same number of columns as fms'; end [~,nCol] = size(data); if(nColH ~= nCol) error 'data must have same number of columns as headings'; end % % end basic checking on input, now do the formating and printing % fmt = arrayfun(@(x) ['%',num2str(wid),'s'],1:nCol,'UniformOutput',false); if flag fprintf(fid,[fmt{:} '\n'],headings{:}); end hd=sprintf([fmt{:} '\n'],headings{:}); fmt = arrayfun(@(x) ['%',num2str(wid),fms{x}],1:nCol,'UniformOutput',false); if flag fprintf(fid,[fmt{:} '\n'],data'); end bdy=sprintf([fmt{:} '\n'],data'); end