1 ## Copyright (C) 1993-2012 John W. Eaton
3 ## This file is part of Octave.
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ## General Public License for more details.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {} int2str (@var{n})
21 ## Convert an integer (or array of integers) to a string (or a character
29 ## s = int2str ([1, 2, 3; 4, 5, 6])
36 ## Attr Name Size Bytes Class
37 ## ==== ==== ==== ===== =====
42 ## This function is not very flexible. For better control over the
43 ## results, use @code{sprintf} (@pxref{Formatted Output}).
44 ## @seealso{sprintf, num2str, mat2str}
49 function retval = int2str (n)
65 idx = repmat ({':'}, nd, 1);
67 ifmt = get_fmt (n(idx{:}), 0);
69 rfmt = get_fmt (n(idx{:}), 2);
70 fmt = cstrcat (ifmt, repmat (rfmt, 1, nc-1), "\n");
72 fmt = cstrcat (get_fmt (n, 0), "\n");
74 tmp = sprintf (fmt, permute (n, [2, 1, 3 : nd]));
76 retval = char (strsplit (tmp, "\n"));
80 function fmt = get_fmt (x, sep)
86 fmt = sprintf ("%%%dd", 1 + sep);
88 ## Maybe have some zeros.
89 nan_inf = isinf (t) | isnan (t);
91 if (any (t(nan_inf) < 0))
101 ## Only zeros, Inf, and NaN.
102 fmt = sprintf ("%%%dd", min_fw);
104 ## Could have anything.
105 tfw = floor (log10 (double (abs (t)))) + 1 + sep;
107 if (any (t(tfw == fw) < 0))
110 fmt = sprintf ("%%%dd", max (fw, min_fw));
116 %!assert (strcmp (int2str (-123), "-123") && strcmp (int2str (1.2), "1"));
117 %!assert (all (int2str ([1, 2, 3; 4, 5, 6]) == ["1 2 3";"4 5 6"]));
118 %!assert (int2str([]), "");
121 %!error int2str (1, 2);