changeset 31371:c549b2401c38

maint: Merge stable to default.
author Nicholas R. Jankowski <jankowski.nicholas@gmail.com>
date Mon, 31 Oct 2022 00:09:01 -0400
parents c0f1a817c058 (current diff) 80bd450892b2 (diff)
children c45fe7ea3153
files etc/NEWS.7.md scripts/statistics/var.m
diffstat 2 files changed, 17 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/etc/NEWS.7.md	Sun Oct 30 10:54:12 2022 -0700
+++ b/etc/NEWS.7.md	Mon Oct 31 00:09:01 2022 -0400
@@ -23,6 +23,7 @@
 - Fix incorrect `lambda` outputs for `lsqnonneg` and `pqpnonneg` (bug #63178).
 - `addtodate.m`: Fix wrong month returned when subtracting a month from some end-of-month dates (bug #60671).
 - `var.m`: Fix some Inf and NaN inputs returning 0 instead of NaN (bug #63203)
+- `var.m`: Fix automatic broadcasting error for sparse and diagonal matrix inputs with vector weighting (bug #63291).
 - `legend.m`: Fix error with `contour` plot containing `clabel`s (bug #63262).
 - `dec2bin.m`: Fix input validation (bug #63089).
 - `glpk.m`: Avoid using `isfinite` on potentially sparse input.
--- a/scripts/statistics/var.m	Sun Oct 30 10:54:12 2022 -0700
+++ b/scripts/statistics/var.m	Mon Oct 31 00:09:01 2022 -0400
@@ -224,8 +224,14 @@
         w = reshape (w, newdims);
       endif
       den = sum (w);
-      mu = sum (w .* x, dim) ./ den;
-      v = sum (w .* ((x - mu) .^ 2), dim) ./ den;
+
+      ## FIXME: Use bsxfun, rather than broadcasting, until broadcasting
+      ##        supports diagonal and sparse matrices (Bugs #41441, #35787).
+      mu = sum (bsxfun (@times, w , x), dim) ./ den;
+      v = sum (bsxfun (@times, w, ...
+                            bsxfun (@minus, x, mu) .^ 2), dim) ./ den;
+      ## mu = sum (w .* x, dim) ./ den; # automatic broadcasting
+      ## v = sum (w .* ((x - mu) .^ 2), dim) ./ den;
     endif
   endif
 
@@ -417,6 +423,14 @@
 %! assert (v, [2, 2, NaN]);
 %! assert (m, [2, 4, NaN]);
 
+## Test sparse/diagonal inputs
+%!assert <*63291> (var (2 * eye (2)), [2, 2])
+%!assert <*63291> (var (4 * eye (2), [1, 3]), [3, 3])
+%!assert <*63291> (full (var (sparse (2 * eye (2)))), [2, 2])
+%!assert <*63291> (full (var (sparse (4 * eye (2)), [1, 3])), [3, 3])
+%!assert <63291> (issparse (var (sparse (2 * eye (2)))))
+%!assert <63291> (issparse (var (sparse (4 * eye (2)), [1, 3])))
+
 ## Test input validation
 %!error <Invalid call> var ()
 %!error <X must be a numeric> var (['A'; 'B'])