changeset 33222:67480f3843c7

hist.m: allow processing of n-D array inputs (bug #65478) * hist.m: Add check for N-D inputs and flatten to 2-D. Update docstring regarding output shape. Add BISTs. * NEWS.10.md: Note change under General Improvements.
author Nicholas R. Jankowski <jankowski.nicholas@gmail.com>
date Mon, 18 Mar 2024 17:34:56 -0400
parents 3af3c114f706
children d174bfd66e28
files etc/NEWS.10.md scripts/plot/draw/hist.m
diffstat 2 files changed, 26 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/etc/NEWS.10.md	Mon Mar 18 17:30:43 2024 +0100
+++ b/etc/NEWS.10.md	Mon Mar 18 17:34:56 2024 -0400
@@ -24,6 +24,10 @@
 
 - `jsonencode` now outputs integers and floating point integers without ".0"
   suffix.
+  
+- `hist` now accepts N-dimensional array inputs for input `Y` which is
+  processed in columns as if the array was flattened to a 2-dimensional
+  array.
 
 ### Graphical User Interface
 
--- a/scripts/plot/draw/hist.m	Mon Mar 18 17:30:43 2024 +0100
+++ b/scripts/plot/draw/hist.m	Mon Mar 18 17:34:56 2024 -0400
@@ -84,8 +84,8 @@
 ## @var{nn} (numbers of elements) and @var{xx} (bin centers) such that
 ## @code{bar (@var{xx}, @var{nn})} will plot the histogram.  If @var{y} is a
 ## vector, @var{nn} and @var{xx} will be row vectors.  If @var{y} is an array,
-## @var{nn} will be an array with one column of element counts for each column
-## in @var{y}, and @var{xx} will be a column vector of bin centers.
+## @var{nn} will be a 2-D array with one column of element counts for each
+## column in @var{y}, and @var{xx} will be a column vector of bin centers.
 ##
 ## @seealso{histc, bar, pie, rose}
 ## @end deftypefn
@@ -193,6 +193,11 @@
     norm = norm (:).';  # Ensure vector orientation.
   endif
 
+  ## Flatten y from N-D to 2-D array
+  if (ndims (y) > 2)
+    y = y(:,:);
+  endif
+
   ## Perform histogram calculation
   cutoff = (x(1:end-1,:) + x(2:end,:)) / 2;
 
@@ -409,6 +414,21 @@
 %! [nn, xx] = hist (double (1:10), single ([1, 5, 10]));
 %! assert (isa (xx, "single"));
 
+## Test N-D arrays produce the same result as 2-D arrays
+%!test <*65478>  # Small n
+%! a = magic (4);
+%! b = permute (a, [1, 3, 2]);
+%! [na, xa] = hist (a);
+%! [nb, xb] = hist (b);
+%! assert ({na, xa}, {nb, xb});
+
+%!test <*65478>  # Large n
+%! a = magic (4);
+%! b = permute (a, [1, 3, 2]);
+%! [na, xa] = hist (a, 30);
+%! [nb, xb] = hist (b, 30);
+%! assert ({na, xa}, {nb, xb});
+
 ## Test input validation
 %!error <Invalid call> hist ()
 %!error <Y must be real-valued> hist (2+i)