comparison scripts/strings/base2dec.m @ 13164:36afcd6fc45f

Allow cellstr inputs to *2dec conversion functions (Bug #34147). * base2dec.m, bin2dec.m, hex2dec.m: Allow cellstr inputs. Amend documentation for new feature and add test for new behavior.
author Rik <octave@nomad.inbox5.com>
date Mon, 19 Sep 2011 17:15:07 -0700
parents fd0a3ac60b0e
children 72c96de7a403
comparison
equal deleted inserted replaced
13163:2ca9730d35ba 13164:36afcd6fc45f
26 ## base2dec ("11120", 3) 26 ## base2dec ("11120", 3)
27 ## @result{} 123 27 ## @result{} 123
28 ## @end group 28 ## @end group
29 ## @end example 29 ## @end example
30 ## 30 ##
31 ## If @var{s} is a matrix, returns a column vector with one value per 31 ## If @var{s} is a string matrix, return a column vector with one value per
32 ## row of @var{s}. If a row contains invalid symbols then the 32 ## row of @var{s}. If a row contains invalid symbols then the
33 ## corresponding value will be NaN@. Rows are right-justified before 33 ## corresponding value will be NaN@.
34 ## converting so that trailing spaces are ignored. 34 ##
35 ## If @var{s} is a cell array of strings, return a column vector with one
36 ## value per cell element in @var{s}.
35 ## 37 ##
36 ## If @var{base} is a string, the characters of @var{base} are used as the 38 ## If @var{base} is a string, the characters of @var{base} are used as the
37 ## symbols for the digits of @var{s}. Space (' ') may not be used as a 39 ## symbols for the digits of @var{s}. Space (' ') may not be used as a
38 ## symbol. 40 ## symbol.
39 ## 41 ##
51 53
52 function out = base2dec (s, base) 54 function out = base2dec (s, base)
53 55
54 if (nargin != 2) 56 if (nargin != 2)
55 print_usage (); 57 print_usage ();
58 endif
59
60 if (iscellstr (s))
61 s = char (s);
62 elseif (! ischar (s))
63 error ("base2dec: S must be a string or cellstring");
56 endif 64 endif
57 65
58 symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 66 symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
59 if (ischar (base)) 67 if (ischar (base))
60 symbols = base; 68 symbols = base;
87 ## and sum the rows. 95 ## and sum the rows.
88 out = s * (base .^ (columns(s)-1 : -1 : 0)'); 96 out = s * (base .^ (columns(s)-1 : -1 : 0)');
89 97
90 endfunction 98 endfunction
91 99
100
92 %!assert(base2dec ("11120", 3), 123); 101 %!assert(base2dec ("11120", 3), 123);
93 %!assert(base2dec ("yyyzx", "xyz"), 123); 102 %!assert(base2dec ("yyyzx", "xyz"), 123);
94 %!assert(base2dec ("-1", 2), NaN); 103 %!assert(base2dec ("-1", 2), NaN);
104 %!assert(base2dec ({"A1", "1A"}, 16), [161; 26]);
95 105
96 %%Test input validation 106 %%Test input validation
97 %!error base2dec (); 107 %!error base2dec ();
98 %!error base2dec ("11120"); 108 %!error base2dec ("11120");
99 %!error base2dec ("11120", 3, 4); 109 %!error base2dec ("11120", 3, 4);