From octave-sources-request at bevo dot che dot wisc dot edu Fri Jul 18 07:51:00 2003 Subject: num2str From: Matthias Jueschke To: octave-sources at bevo dot che dot wisc dot edu Date: Fri, 18 Jul 2003 14:49:41 +0200 (MET DST) Since I didn't find a num2str for octave which handeles matrices and complex numbers, I have written one. % Copyright (C) 2003 Matthias Jueschke % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, % USA. % % Author: Matthias Jueschke % Description: Function for octave which formats matrices as a string. function retval = num2str(x) %retval = num2str(x) % Format x as a string. % % See also: sprintf, int2str if (nargin ~= 1) usage ("num2str (x)"); break; end if all(round(x)==x) & (max(max([real(abs(x)); imag(abs(x))])) < 1/eps) % integer values if any(real(x)) realN = fix(max(max( log10(abs(real(x))) )))+1; else realN = 1; end formatR = ["'%" sprintf("%i",realN) ".0f'\n"]; if is_complex(x) imagN = fix(max(max( log10(abs(real(x))) )))+1; formatI = ["'%-+" sprintf("%i",imagN) ".0fi'\n"]; end else % real values formatR = ["'%" sprintf("%i",12) "g'\n"]; formatI = ["'%-+gi'\n"]; end retval = eval([ "[" sprintf(formatR, real(x(:,1))) "];" ]); % erase leading spaces while all(retval(:,1)==" ") retval = retval(:,2:columns(retval)); end if is_complex(x) h = [ "[" sprintf(formatI, imag(x(:,1))) "];" ]; retval = [retval, eval(h)]; end for j = 2:columns(x) retval(:,columns(retval)+1:columns(retval)+2) = ' '; h = [ "[" sprintf(formatR, real(x(:,j))) "];" ]; retval = [retval, eval(h)]; if is_complex(x) h = [ "[" sprintf(formatI, imag(x(:,j))) "];" ]; retval = [retval, eval(h)]; end end