changeset 12006:6628023f72dcrelease-3-2-x

fix var for scalar and empty arguments
author John W. Eaton Tue, 23 Jun 2009 12:57:57 +0200 d3b6e85aaf53 dc56a38b5a64 scripts/ChangeLog scripts/statistics/base/var.m 2 files changed, 36 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
```--- a/scripts/ChangeLog
+++ b/scripts/ChangeLog
@@ -1,3 +1,8 @@
+2009-06-22  John W. Eaton  <jwe@octave.org>
+
+	* statistics/base/var.m: Return zero for scalar case.  Handle
+	empty arguments in a Matlab compatible way.  New tests.
+
2009-06-18  Ben Abbott <bpabbott@mac.com>

* plot/__go_draw_axes__.m: Change the default x11 fontspec from '*,0'```
```--- a/scripts/statistics/base/var.m
+++ b/scripts/statistics/base/var.m
@@ -56,13 +56,39 @@
opt = 0;
endif

-  n = size (x, dim);
-  if (n == 1)
+  sz = size (x);
+  n = sz(dim);
+  if (isempty (x))
+    ## FIXME -- is there a way to obtain these results without all the
+    ## special cases?
+    if (ndim (x) == 2 && sz(0) == 0 && sz(1) == 0)
+      retval = NaN;
+    else
+      sz(dim) = 1;
+      if (n == 0)
+	if (prod (sz) == 0)
+	  retval = zeros (sz);
+	else
+	  retval = NaN (sz);
+	endif
+      else
+	retval = zeros (sz);
+      endif
+    endif
+  elseif (n == 1)
retval = zeros (sz);
-  elseif (numel (x) > 0)
+  else
retval = sumsq (center (x, dim), dim) / (n + opt - 1);
-  else
-    error ("var: x must not be empty");
endif

endfunction
+
+%!assert (var (13), 0)
+%!assert (var ([]), NaN)
+%!assert (var (ones (0, 0, 0), 0, 1), zeros (1, 0, 0))
+%!assert (var (ones (0, 0, 0), 0, 2), zeros (0, 1, 0))
+%!assert (var (ones (0, 0, 0), 0, 3), zeros (0, 0))
+%!assert (var (ones (1, 2, 0)), zeros (1, 1, 0))
+%!assert (var (ones (1, 2, 0, 0), 0, 1), zeros (1, 2, 0, 0))
+%!assert (var (ones (1, 2, 0, 0), 0, 2), zeros (1, 1, 0, 0))
+%!assert (var (ones (1, 2, 0, 0), 0, 3), zeros (1, 2, 1, 0))```