changeset 31870:6a2638cbea96

maint: Update code in cset c6eeb8b44c28 to use Octave core coding conventions (patch #10314). * mean.m, median.m, std.m, var.m: Reset Copyright dates back to original ones. Wrap long lines in documentation. Use two spaces after sentence ending period. Use boolean values (true/false) rather than 0/1 for flags. Rename variable 'i' to "argin" for clarity in option processiong. Don't end error() messages with a period '.'. Use a semicolon at end of error() function calls. Use parentheses around conditional in if statement. Remove excess parentheses in if statements. Use feval() to directly cast output to "outtype" rather than cast(). Use "FIXME:" for items which need to be examined later. Use in-place addition operator for performance. Use one '#' for comments trailing code and "##" for full-line comments. Don't use semicolons at end of %!assert statements. Use space between logical not operator '!' and argument that follows.
author Rik <rik@octave.org>
date Wed, 01 Mar 2023 19:46:20 -0800
parents 0149a2f4ac98
children 9546e993e9ee
files scripts/statistics/mean.m scripts/statistics/median.m scripts/statistics/std.m scripts/statistics/var.m
diffstat 4 files changed, 279 insertions(+), 304 deletions(-) [+]
line wrap: on
line diff
--- a/scripts/statistics/mean.m	Wed Mar 01 12:40:50 2023 -0500
+++ b/scripts/statistics/mean.m	Wed Mar 01 19:46:20 2023 -0800
@@ -1,6 +1,6 @@
 ########################################################################
 ##
-## Copyright (C) 1996-2023 The Octave Project Developers
+## Copyright (C) 1995-2023 The Octave Project Developers
 ##
 ## See the file COPYRIGHT.md in the top-level directory of this
 ## distribution or <https://octave.org/copyright/>.
@@ -32,8 +32,8 @@
 ## @deftypefnx {} {@var{m} =} mean (@dots{}, @var{outtype})
 ## Compute the mean of the elements of @var{x}.
 ##
-## If @var{x} is a vector, then @code{mean (@var{x})} returns the
-## mean of the elements in @var{x} defined as
+## If @var{x} is a vector, then @code{mean (@var{x})} returns the mean of the
+## elements in @var{x} defined as
 ## @tex
 ## $$ {\rm mean}(x) = \bar{x} = {1\over N} \sum_{i=1}^N x_i $$
 ## where $N$ is the number of elements of @var{x}.
@@ -49,8 +49,8 @@
 ##
 ## @end ifnottex
 ##
-## If @var{x} is an array, then @code{mean(@var{x})} computes the mean along the
-## first nonsingleton dimension of @var{x}.
+## If @var{x} is an array, then @code{mean(@var{x})} computes the mean along
+## the first nonsingleton dimension of @var{x}.
 ##
 ## The optional variable @var{dim} forces @code{mean} to operate over the
 ## specified dimension, which must be a positive integer-valued number.
@@ -59,9 +59,9 @@
 ##
 ## Specifying the dimensions as  @var{vecdim}, a vector of non-repeating
 ## dimensions, will return the mean over the array slice defined by
-## @var{vecdim}. If @var{vecdim} indexes all dimensions of @var{x}, then it is
-## equivalent to the option @qcode{"all"}. Any dimension in @var{vecdim} greater
-## than @code{ndims (@var{x})} is ignored.
+## @var{vecdim}.  If @var{vecdim} indexes all dimensions of @var{x}, then it is
+## equivalent to the option @qcode{"all"}.  Any dimension in @var{vecdim}
+## greater than @code{ndims (@var{x})} is ignored.
 ##
 ## Specifying the dimension as @qcode{"all"} will force @code{mean} to operate
 ## on all elements of @var{x}, and is equivalent to @code{mean (@var{x}(:))}.
@@ -82,10 +82,11 @@
 ##
 ## The optional variable @var{nanflag} specifies whether to include or exclude
 ## NaN values from the calculation using any of the previously specified input
-## argument combinations.  The default value for @var{nanflag} is "includenan"
-## which keeps NaN values in the calculation. To exclude NaN values set the
-## value of @var{nanflag} to "omitnan".  The output will still contain NaN
-## values if @var{x} consists of all NaN values in the operating dimension.
+## argument combinations.  The default value for @var{nanflag} is
+## @qcode{"includenan"} which keeps NaN values in the calculation.  To exclude
+## NaN values set the value of @var{nanflag} to @qcode{"omitnan"}.  The output
+## will still contain NaN values if @var{x} consists of all NaN values in the
+## operating dimension.
 ##
 ## @seealso{median, mode, movmean}
 ## @end deftypefn
@@ -97,9 +98,9 @@
   endif
 
   ## Set initial conditions
-  all_flag = 0;
-  omitnan = 0;
-  out_flag = 0;
+  all_flag = false;
+  omitnan  = false;
+  out_flag = false;
 
   nvarg = numel (varargin);
   varg_chars = cellfun ("ischar", varargin);
@@ -114,8 +115,8 @@
 
   ## Process any other char arguments.
   if (any (varg_chars))
-    for i = varargin(varg_chars)
-      switch (lower (i{:}))
+    for argin = varargin(varg_chars)
+      switch (lower (argin{:}))
         case "all"
           all_flag = true;
 
@@ -127,32 +128,32 @@
 
         case "default"
           if (out_flag)
-            error ("mean: only one OUTTYPE can be specified.")
+            error ("mean: only one OUTTYPE can be specified");
           endif
           if (isa (x, "single"))
             outtype = "single";
           else
             outtype = "double";
           endif
-          out_flag = 1;
+          out_flag = true;
 
         case "native"
           outtype = class (x);
           if (out_flag)
-            error ("mean: only one OUTTYPE can be specified.")
+            error ("mean: only one OUTTYPE can be specified");
           elseif (strcmp (outtype, "logical"))
             outtype = "double";
           elseif (strcmp (outtype, "char"))
-            error ("mean: OUTTYPE 'native' cannot be used with char inputs.");
+            error ("mean: OUTTYPE 'native' cannot be used with char inputs");
           endif
-          out_flag = 1;
+          out_flag = true;
 
         case "double"
           if (out_flag)
-            error ("mean: only one OUTTYPE can be specified.")
+            error ("mean: only one OUTTYPE can be specified");
           endif
           outtype = "double";
-          out_flag = 1;
+          out_flag = true;
 
         otherwise
           print_usage ();
@@ -162,7 +163,7 @@
     nvarg = numel (varargin);
   endif
 
-  if strcmp (outtype, "default")
+  if (strcmp (outtype, "default"))
     if (isa (x, "single"))
       outtype = "single";
     else
@@ -170,16 +171,16 @@
     endif
   endif
 
-  if ((nvarg > 1) || ((nvarg == 1) && ! (isnumeric (varargin{1}))))
+  if (nvarg > 1 || (nvarg == 1 && ! isnumeric (varargin{1})))
     ## After trimming char inputs can only be one varargin left, must be numeric
     print_usage ();
   endif
 
   if (! (isnumeric (x) || islogical (x) || ischar (x)))
-    error ("mean: X must be either a numeric, boolean, or character array.");
+    error ("mean: X must be either a numeric, boolean, or character array");
   endif
 
-  ## Process special cases for in/out size
+  ## Process special cases of input/output sizes.
   if (nvarg == 0)
     ## Single numeric input argument, no dimensions given.
 
@@ -218,14 +219,14 @@
 
     ## Two numeric input arguments, dimensions given.  Note scalar is vector!
     vecdim = varargin{1};
-    if (isempty (vecdim) || ! (isvector (vecdim) && all (vecdim > 0)) ...
-          || any (rem (vecdim, 1)))
-      error ("mean: DIM must be a positive integer scalar or vector.");
+    if (isempty (vecdim) || ! (isvector (vecdim) && all (vecdim > 0))
+        || any (rem (vecdim, 1)))
+      error ("mean: DIM must be a positive integer scalar or vector");
     endif
 
     if (ndx == 2 && isempty (x) && szx == [0,0])
-      ## FIXME: this special case handling could be removed once sum
-      ##        compatably handles all sizes of empty inputs
+      ## FIXME: This special case handling could be removed once sum
+      ##        compatibly handles all sizes of empty inputs.
       sz_out = szx;
       sz_out (vecdim(vecdim <= ndx)) = 1;
       m = NaN (sz_out);
@@ -253,22 +254,21 @@
       else
         vecdim = sort (vecdim);
         if (! all (diff (vecdim)))
-           error ("mean: VECDIM must contain non-repeating positive integers.");
+           error ("mean: VECDIM must contain non-repeating positive integers");
         endif
-        ## Ignore exceeding dimensions in VECDIM
-        vecdim(find (vecdim > ndims (x))) = [];
+        ## Ignore dimensions in VECDIM larger than actual array.
+        vecdim(vecdim > ndims (x)) = [];
 
         if (isempty (vecdim))
           m = x;
         else
-          ## Move vecdims to dim 1.
 
           ## Calculate permutation vector
-          remdims = 1 : ndx;    # All dimensions
-          remdims(vecdim) = [];     # Delete dimensions specified by vecdim
+          remdims = 1 : ndx;     # All dimensions
+          remdims(vecdim) = [];  # Delete dimensions specified by vecdim
           nremd = numel (remdims);
 
-          ## If all dimensions are given, it is similar to all flag
+          ## If all dimensions are given, it is equivalent to 'all' flag
           if (nremd == 0)
             x = x(:);
             if (omitnan)
@@ -282,30 +282,28 @@
             endif
 
           else
-            ## Permute to bring vecdims to front
-            perm = [vecdim, remdims];
+            ## Permute to push vecdims to back
+            perm = [remdims, vecdim];
             x = permute (x, perm);
 
-            ## Reshape to squash all vecdims in dim1
-            num_dim = prod (szx(vecdim));
-            szx(vecdim) = [];
-            szx = [ones(1, numel(vecdim)), szx];
-            szx(1) = num_dim;
-            x = reshape (x, szx);
+            ## Reshape to squash all vecdims in final dimension
+            sznew = [szx(remdims), prod(szx(vecdim))];
+            x = reshape (x, sznew);
 
-            ## Calculate mean on dim1
+            ## Calculate mean on final dimension
+            dim = nremd + 1;
             if (omitnan)
               nanx = isnan (x);
               x(nanx) = 0;
-              n = sum (! nanx, 1);
+              n = sum (! nanx, dim);
             else
-              n = szx(1);
+              n = sznew(dim);
             endif
 
             if (any (isa (x, {"int64", "uint64"})))
-              m = int64_mean (x, 1, n, outtype);
+              m = int64_mean (x, dim, n, outtype);
             else
-              m = sum (x, 1) ./ n;
+              m = sum (x, dim) ./ n;
             endif
 
             ## Inverse permute back to correct dimensions
@@ -316,19 +314,13 @@
     endif
   endif
 
-  ## Convert output as requested
+  ## Convert output if necessary
   if (! strcmp (class (m), outtype))
-    switch (outtype)
-      case "double"
-        m = double (m);
-      case "single"
-        m = single (m);
-      otherwise
-        if (! islogical (x))
-          m = cast (m, outtype);
-        endif
-    endswitch
+    if (! islogical (x))
+      m = feval (outtype, m);
+    endif
   endif
+
 endfunction
 
 function m = int64_mean (x, dim, n, outtype)
@@ -354,10 +346,10 @@
 
       if (any (abs (m(:)) >= flintmax))
         ## Avoid float errors when combining for large m.
-        ## FIXME - may also need to include checking rmdir for large numel (x),
-        ## as its value could be on the order of numel (x).
+        ## FIXME: may also need to include checking rmdr for large numel (x),
+        ##        as its value could be on the order of numel (x).
         if (any (strcmp (outtype, {"int64", "uint64"})))
-          m = m + rmdr;
+          m += rmdr;
         else
           m = double (m) + rmdr;
         endif
@@ -374,8 +366,10 @@
     else
       m = double (sum (x, dim, "native")) ./ n;
     endif
+
 endfunction
 
+
 %!test
 %! x = -10:10;
 %! y = x';
@@ -390,7 +384,7 @@
 %!assert (mean (single ([1 0 1 1])), single (0.75))
 %!assert (mean ([1 2], 3), [1 2])
 
-#### Test outtype option
+## Test outtype option
 %!test
 %! in = [1 2 3];
 %! out = 2;
@@ -440,7 +434,7 @@
 %! assert (mean (in, "native"), uint8 (out_u8));
 %! assert (class (mean (in, "native")), "uint8");
 
-%!test ## internal sum exceeding intmax
+%!test # internal sum exceeding intmax
 %! in = uint8 ([3 141 141 255]);
 %! out = 135;
 %! assert (mean (in, "default"), mean (in));
@@ -449,7 +443,7 @@
 %! assert (mean (in, "native"), uint8 (out));
 %! assert (class (mean (in, "native")), "uint8");
 
-%!test ## fractional answer with interal sum exceeding intmax
+%!test # fractional answer with internal sum exceeding intmax
 %! in = uint8 ([1 141 141 255]);
 %! out = 134.5;
 %! out_u8 = 135;
@@ -459,7 +453,7 @@
 %! assert (mean (in, "native"), uint8 (out_u8));
 %! assert (class (mean (in, "native")), "uint8");
 
-%!test <54567> ## large int64 sum exceeding intmax and double precision limit
+%!test <54567> # large int64 sum exceeding intmax and double precision limit
 %! in_same = uint64 ([intmax("uint64") intmax("uint64")-2]);
 %! out_same = intmax ("uint64")-1;
 %! in_opp = int64 ([intmin("int64"), intmax("int64")-1]);
@@ -504,7 +498,7 @@
 %! assert (mean ([intmin("int64"), in, intmax("int64")]), double(-0.5))
 %! assert (mean ([in; int64([1 3])], 2, "native"), int64([-1; 2]));
 
-## Test input and optional arguments "all", DIM, "omitnan")
+## Test input and optional arguments "all", DIM, "omitnan".
 %!test
 %! x = [-10:10];
 %! y = [x;x+5;x-5];
@@ -526,7 +520,7 @@
 %! assert (mean (z, 2, "native", "omitnan"), m');
 %! assert (mean (z, 2, "omitnan", "native"), m');
 
-# Test boolean input
+## Test boolean input
 %!test
 %! assert (mean (true, "all"), 1);
 %! assert (mean (false), 0);
@@ -579,7 +573,7 @@
 %!assert (mean (ones(0,0,1,0), 2), NaN(0,1,1,0))
 %!assert (mean (ones(0,0,1,0), 3), NaN(0,0,1,0))
 
-## Test dimension indexing with vecdim in n-dimensional arrays
+## Test dimension indexing with vecdim in N-dimensional arrays
 %!test
 %! x = repmat ([1:20;6:25], [5 2 6 3]);
 %! assert (size (mean (x, [3 2])), [10 1 1 3]);
@@ -589,11 +583,11 @@
 %! assert (size (mean (x, [1 2 3 4])), [1 1]);
 
 ## Test exceeding dimensions
-%!assert (mean (ones (2,2), 3), ones (2,2));
-%!assert (mean (ones (2,2,2), 99), ones (2,2,2));
-%!assert (mean (magic (3), 3), magic (3));
-%!assert (mean (magic (3), [1 3]), [5, 5, 5]);
-%!assert (mean (magic (3), [1 99]), [5, 5, 5]);
+%!assert (mean (ones (2,2), 3), ones (2,2))
+%!assert (mean (ones (2,2,2), 99), ones (2,2,2))
+%!assert (mean (magic (3), 3), magic (3))
+%!assert (mean (magic (3), [1 3]), [5, 5, 5])
+%!assert (mean (magic (3), [1 99]), [5, 5, 5])
 
 ## Test results with vecdim in n-dimensional arrays and "omitnan"
 %!test
@@ -607,9 +601,9 @@
 %! assert (mean (x, [3 2], "omitnan"), m, 4e-14);
 
 ## Test input case insensitivity
-%!assert (mean ([1 2 3], "aLL"), 2);
-%!assert (mean ([1 2 3], "OmitNan"), 2);
-%!assert (mean ([1 2 3], "DOUBle"), 2);
+%!assert (mean ([1 2 3], "aLL"), 2)
+%!assert (mean ([1 2 3], "OmitNan"), 2)
+%!assert (mean ([1 2 3], "DOUBle"), 2)
 
 ## Test input validation
 %!error <Invalid call to mean.  Correct usage is> mean ()
--- a/scripts/statistics/median.m	Wed Mar 01 12:40:50 2023 -0500
+++ b/scripts/statistics/median.m	Wed Mar 01 19:46:20 2023 -0800
@@ -55,8 +55,8 @@
 ##
 ## @end ifnottex
 ##
-## If @var{x} is a array, then @code{median (@var{x})} operates along the first
-## non-singleton dimension of @var{x}.
+## If @var{x} is an array, then @code{median (@var{x})} operates along the
+## first non-singleton dimension of @var{x}.
 ##
 ## The optional variable @var{dim} forces @code{median} to operate over the
 ## specified dimension, which must be a positive integer-valued number.
@@ -65,36 +65,38 @@
 ##
 ## Specifying the dimensions as  @var{vecdim}, a vector of non-repeating
 ## dimensions, will return the median over the array slice defined by
-## @var{vecdim}. If @var{vecdim} indexes all dimensions of @var{x}, then it is
-## equivalent to the option @qcode{"all"}. Any dimension in @var{vecdim} greater
-## than @code{ndims (@var{x})} is ignored.
+## @var{vecdim}.  If @var{vecdim} indexes all dimensions of @var{x}, then it is
+## equivalent to the option @qcode{"all"}.  Any dimension in @var{vecdim}
+## greater than @code{ndims (@var{x})} is ignored.
 ##
-## Specifying the dimension as @qcode{"all"} will force @code{median} to operate
-## on all elements of @var{x}, and is equivalent to @code{median (@var{x}(:))}.
+## Specifying the dimension as @qcode{"all"} will force @code{median} to
+## operate on all elements of @var{x}, and is equivalent to
+## @code{median (@var{x}(:))}.
 ##
 ## @code{median (@dots{}, @var{outtype})} returns the median with a specified
 ## data type, using any of the input arguments in the previous syntaxes.
 ## @var{outtype} can take the following values:
 ##
 ## @table @asis
-## @item "default"
-## Output is of type double, unless the input is single in which case the output
-## is of type single.
+## @item @qcode{"default"}
+## Output is of type double, unless the input is single in which case the
+## output is of type single.
 ##
-## @item "double"
+## @item @qcode{"double"}
 ## Output is of type double.
 ##
-## @item "native".
+## @item @qcode{"native"}.
 ## Output is of the same type as the input (@code{class (@var{x})}), unless the
 ## input is logical in which case the output is of type double.
 ## @end table
 ##
 ## The optional variable @var{nanflag} specifies whether to include or exclude
 ## NaN values from the calculation using any of the previously specified input
-## argument combinations.  The default value for @var{nanflag} is "includenan"
-## which keeps NaN values in the calculation. To exclude NaN values set the
-## value of @var{nanflag} to "omitnan".  The output will still contain NaN
-## values if @var{x} consists of all NaN values in the operating dimension.
+## argument combinations.  The default value for @var{nanflag} is
+## @qcode{"includenan"} which keeps NaN values in the calculation.  To
+## exclude NaN values set the value of @var{nanflag} to @qcode{"omitnan"}. 
+## The output will still contain NaN values if @var{x} consists of all NaN
+## values in the operating dimension.
 ##
 ## @seealso{mean, mode, movmedian}
 ## @end deftypefn
@@ -106,16 +108,16 @@
   endif
 
   if (! (isnumeric (x) || islogical (x)))
-    error ("median: X must be either numeric or logical.");
+    error ("median: X must be either numeric or logical");
   endif
 
   ## Set initial conditions
-  all_flag = 0;
-  omitnan = 0;
-  perm_flag = 0;
-  out_flag = 0;
-  vecdim_flag = 0;
-  dim = [];
+  all_flag    = false;
+  omitnan     = false;
+  perm_flag   = false;
+  out_flag    = false;
+  vecdim_flag = false;
+  dim         = [];
 
   nvarg = numel (varargin);
   varg_chars = cellfun ("ischar", varargin);
@@ -130,41 +132,41 @@
 
   ## Process any other char arguments.
   if (any (varg_chars))
-    for idx = varargin(varg_chars)
-      switch (tolower (idx{:}))
+    for argin = varargin(varg_chars)
+      switch (lower (argin{1}))
         case "all"
-          all_flag = 1;
+          all_flag = true;
 
         case "omitnan"
-          omitnan = 1;
+          omitnan = true;
 
         case "includenan"
-          omitnan = 0;
+          omitnan = false;
 
         case "native"
           if (out_flag)
-            error ("median: only one OUTTYPE can be specified.")
+            error ("median: only one OUTTYPE can be specified");
           endif
           if (strcmp (outtype, "logical"))
             outtype = "double";
           endif
-          out_flag = 1;
+          out_flag = true;
 
         case "default"
           if (out_flag)
-            error ("median: only one OUTTYPE can be specified.")
+            error ("median: only one OUTTYPE can be specified");
           endif
           if (! strcmp (outtype, "single"))
             outtype = "double";
           endif
-          out_flag = 1;
+          out_flag = true;
 
         case "double"
           if (out_flag)
-            error ("median: only one OUTTYPE can be specified.")
+            error ("median: only one OUTTYPE can be specified");
           endif
           outtype = "double";
-          out_flag = 1;
+          out_flag = true;
 
         otherwise
           print_usage ();
@@ -175,7 +177,7 @@
     nvarg = numel (varargin);
   endif
 
-  if (((nvarg == 1) && ! (isnumeric (varargin{1}))) || (nvarg > 1))
+  if ((nvarg == 1 && ! isnumeric (varargin{1})) || nvarg > 1)
     ## After trimming char inputs should only be one numeric varargin left
     print_usage ();
   endif
@@ -184,14 +186,14 @@
   if (nvarg > 0)
     ## dim or vecdim provided
     if (all_flag)
-      error ("median: 'all' cannot be used with DIM or VECDIM options.");
+      error ("median: 'all' cannot be used with DIM or VECDIM options");
     endif
 
     dim = varargin{1};
     vecdim_flag = ! isscalar (dim);
 
-    if (! (isvector (dim) && (dim > 0)) || any (rem (dim, 1)))
-      error ("median: DIM must be a positive integer scalar or vector.");
+    if (! (isvector (dim) && dim > 0) || any (rem (dim, 1)))
+      error ("median: DIM must be a positive integer scalar or vector");
     endif
 
     ## Adjust sz_out, account for possible dim > ndx by appending singletons
@@ -203,7 +205,7 @@
       ## vecdim - try to simplify first
       dim = sort (dim);
       if (! all (diff (dim)))
-         error ("median: VECDIM must contain non-repeating positive integers.");
+         error ("median: VECDIM must contain non-repeating positive integers");
       endif
 
       ## dims > ndims(x) and dims only one element long don't affect median
@@ -213,13 +215,13 @@
       if (isempty (dim))
         ## No dims left to process, return input as output
         if (! strcmp (class (x), outtype))
-          m = outtype_convert (x, outtype);
+          m = feval (outtype, x);  # convert to outtype
         else
           m = x;
         endif
         return;
-      elseif ((numel(dim) == numel(sing_dim_x)) ...
-                 && unique ([dim, sing_dim_x]) == dim)
+      elseif (numel (dim) == numel (sing_dim_x)
+              && unique ([dim, sing_dim_x]) == dim)
         ## If DIMs cover all nonsingleton ndims(x) it's equivalent to "all"
         ##   (check lengths first to reduce unique overhead if not covered)
         all_flag = true;
@@ -227,9 +229,9 @@
     endif
 
   else
-    ## Dim not provided.  Determine scalar dimension
+    ## Dim not provided.  Determine scalar dimension.
     if (all_flag)
-      ## Special case 'all': Recast input as dim1 vector, process as normal
+      ## Special case 'all': Recast input as dim1 vector, process as normal.
       x = x(:);
       szx = [numel(x), 1];
       dim = 1;
@@ -241,7 +243,7 @@
       sz_out = [1, 1];
 
     elseif (ndx == 2 && szx == [0, 0])
-      ## Special case []: Do not apply sz_out(dim)=1 change
+      ## Special case []: Do not apply sz_out(dim)=1 change.
       dim = 1;
       sz_out = [1, 1];
 
@@ -268,7 +270,7 @@
   if (szx(dim) == 1)
     ## Operation along singleton dimension - nothing to do
     if (! strcmp (class (x), outtype))
-      m = outtype_convert (x, outtype);
+      m = feval (outtype, x);  # convert to outtype
     else
       m = x;
     endif
@@ -276,31 +278,26 @@
   endif
 
   ## Permute dim to simplify all operations along dim1.  At func. end ipermute.
-
-  ## FIXME: for very large data sets, flattening all vecdim dimensions into dim1
-  ##        could hit index type limits
-
-  if ((numel (dim) > 1) || (dim != 1 && ! isvector (x)))
-    perm_vect = 1 : ndx;
+  if (numel (dim) > 1 || (dim != 1 && ! isvector (x)))
+    perm = 1 : ndx;
 
     if (! vecdim_flag)
       ## Move dim to dim 1
-      perm_vect([1, dim]) = [dim, 1];
-      x = permute (x, perm_vect);
+      perm([1, dim]) = [dim, 1];
+      x = permute (x, perm);
       szx([1, dim]) = szx([dim, 1]);
       dim = 1;
 
     else
       ## Move vecdims to front
-      perm_vect(dim) = [];
-      perm_vect = [dim, perm_vect];
-      x = permute (x, perm_vect);
+      perm(dim) = [];
+      perm = [dim, perm];
+      x = permute (x, perm);
 
       ## Reshape all vecdims into dim1
       num_dim = prod (szx(dim));
       szx(dim) = [];
-      szx = [ones(1, numel(dim)), szx];
-      szx(1) = num_dim;
+      szx = [num_dim, ones(1, numel(dim)-1), szx];
       x = reshape (x, szx);
       dim = 1;
     endif
@@ -311,15 +308,15 @@
   ## Find column locations of NaNs
   nanfree = ! any (isnan (x), dim);
   if (omitnan && nanfree(:))
-    ## Don't use omitnan path if no NaNs are present. Prevents any data types
+    ## Don't use omitnan path if no NaNs are present.  Prevents any data types
     ## without a defined NaN from following slower omitnan codepath.
-    omitnan = 0;
+    omitnan = false;
   endif
 
-  x = sort (x, dim); # Note: pushes any NaN's to end for omitnan compatability
+  x = sort (x, dim); # Note: pushes any NaN's to end for omitnan compatibility
 
   if (omitnan)
-    ## Ignore any NaN's in data. Each operating vector might have a
+    ## Ignore any NaN's in data.  Each operating vector might have a
     ## different number of non-NaN data points.
 
     if (isvector (x))
@@ -337,7 +334,7 @@
 
     else
       n = sum (! isnan (x), 1);
-      k = floor ((n + 1) ./ 2);
+      k = floor ((n + 1) / 2);
       m_idx_odd = mod (n, 2) & n;
       m_idx_even = (! m_idx_odd) & n;
 
@@ -361,7 +358,7 @@
     endif
 
   else
-    ## No "omitnan". All 'vectors' uniform length.
+    ## No "omitnan".  All 'vectors' uniform length.
     ## All types without a NaN value will use this path.
     if (all (! nanfree))
       m = NaN (sz_out);
@@ -404,7 +401,7 @@
           if (any (isa (x, "integer")))
             ## avoid int overflow issues
 
-            ## Use flattened index to simplify n-D operations
+            ## Use flattened index to simplify N-D operations
             m(1, :) = x(k, :);
             m2 = x(k + 1, :);
 
@@ -416,7 +413,7 @@
             m(nanfree) = (x(k, nanfree) + x(k + 1, nanfree)) / 2;
           endif
         else
-          ## Odd. Use flattened index to simplify n-D operations
+          ## Odd.  Use flattened index to simplify N-D operations
           m(nanfree) = x(k, nanfree);
         endif
       endif
@@ -425,26 +422,16 @@
 
   if (perm_flag)
     ## Inverse permute back to correct dimensions
-    m = ipermute (m, perm_vect);
+    m = ipermute (m, perm);
   endif
 
   ## Convert output type as requested
   if (! strcmp (class (m), outtype))
-    m = outtype_convert (m, outtype);
+    m = feval (outtype, m);
   endif
 
 endfunction
 
-function m = outtype_convert (m, outtype)
-  switch (outtype)
-    case "single"
-      m = single (m);
-    case "double"
-      m = double (m);
-    otherwise
-      m = cast (m, outtype);
-  endswitch
-endfunction
 
 %!assert (median (1), 1)
 %!assert (median ([1,2,3]), 2)
@@ -513,7 +500,7 @@
 %!assert (median (cat (3, 3, 1, NaN, 2), "omitnan"), 2)
 %!assert (median (cat (3, 3, 1, NaN, 2), 3, "omitnan"), 2)
 
-# Test boolean input
+## Test boolean input
 %!test
 %! assert (median (true, "all"), logical (1));
 %! assert (median (false), logical (0));
@@ -535,11 +522,11 @@
 %! assert (size (median (x, [1 2 3 4])), [1 1]);
 
 ## Test exceeding dimensions
-%!assert (median (ones (2,2), 3), ones (2,2));
-%!assert (median (ones (2,2,2), 99), ones (2,2,2));
-%!assert (median (magic (3), 3), magic (3));
-%!assert (median (magic (3), [1 3]), [4, 5, 6]);
-%!assert (median (magic (3), [1 99]), [4, 5, 6]);
+%!assert (median (ones (2,2), 3), ones (2,2))
+%!assert (median (ones (2,2,2), 99), ones (2,2,2))
+%!assert (median (magic (3), 3), magic (3))
+%!assert (median (magic (3), [1 3]), [4, 5, 6])
+%!assert (median (magic (3), [1 99]), [4, 5, 6])
 
 ## Test results with vecdim in n-dimensional arrays and "omitnan"
 %!test
@@ -578,41 +565,41 @@
 %!assert (median ([NaN 2 ; NaN 4], "omitnan"), [NaN 3])
 %!assert (median (ones (1, 0, 3)), NaN (1, 1, 3))
 
-%!assert (median (NaN("single")), NaN("single"));
-%!assert (median (NaN("single"), "omitnan"), NaN("single"));
-%!assert (median (NaN("single"), "double"), NaN("double"));
-%!assert (median (single([1 2 ; NaN 4])), single([NaN 3]));
-%!assert (median (single([1 2 ; NaN 4]), "double"), double([NaN 3]));
-%!assert (median (single([1 2 ; NaN 4]), "omitnan"), single([1 3]));
-%!assert (median (single([1 2 ; NaN 4]), "omitnan", "double"), double([1 3]));
-%!assert (median (single([NaN 2 ; NaN 4]), "double"), double([NaN 3]));
-%!assert (median (single([NaN 2 ; NaN 4]), "omitnan"), single([NaN 3]));
-%!assert (median (single([NaN 2 ; NaN 4]), "omitnan", "double"), double([NaN 3]));
+%!assert (median (NaN("single")), NaN("single"))
+%!assert (median (NaN("single"), "omitnan"), NaN("single"))
+%!assert (median (NaN("single"), "double"), NaN("double"))
+%!assert (median (single([1 2 ; NaN 4])), single([NaN 3]))
+%!assert (median (single([1 2 ; NaN 4]), "double"), double([NaN 3]))
+%!assert (median (single([1 2 ; NaN 4]), "omitnan"), single([1 3]))
+%!assert (median (single([1 2 ; NaN 4]), "omitnan", "double"), double([1 3]))
+%!assert (median (single([NaN 2 ; NaN 4]), "double"), double([NaN 3]))
+%!assert (median (single([NaN 2 ; NaN 4]), "omitnan"), single([NaN 3]))
+%!assert (median (single([NaN 2 ; NaN 4]), "omitnan", "double"), double([NaN 3]))
 
-%!assert (median (Inf), Inf);
-%!assert (median (-Inf), -Inf);
-%!assert (median ([-Inf Inf]), NaN);
-%!assert (median ([3 Inf]), Inf);
-%!assert (median ([3 4 Inf]), 4);
-%!assert (median ([Inf 3 4]), 4);
-%!assert (median ([Inf 3 Inf]), Inf);
+%!assert (median (Inf), Inf)
+%!assert (median (-Inf), -Inf)
+%!assert (median ([-Inf Inf]), NaN)
+%!assert (median ([3 Inf]), Inf)
+%!assert (median ([3 4 Inf]), 4)
+%!assert (median ([Inf 3 4]), 4)
+%!assert (median ([Inf 3 Inf]), Inf)
 
-%!assert (median ([]), NaN);
-%!assert (median (ones(1,0)), NaN);
-%!assert (median (ones(0,1)), NaN);
-%!assert (median ([], 1), NaN(1,0));
-%!assert (median ([], 2), NaN(0,1));
-%!assert (median ([], 3), NaN(0,0));
-%!assert (median (ones(1,0), 1), NaN(1,0));
-%!assert (median (ones(1,0), 2), NaN(1,1));
-%!assert (median (ones(1,0), 3), NaN(1,0));
-%!assert (median (ones(0,1), 1), NaN(1,1));
-%!assert (median (ones(0,1), 2), NaN(0,1));
-%!assert (median (ones(0,1), 3), NaN(0,1));
-%!assert (median (ones(0,1,0,1), 1), NaN(1,1,0));
-%!assert (median (ones(0,1,0,1), 2), NaN(0,1,0));
-%!assert (median (ones(0,1,0,1), 3), NaN(0,1,1));
-%!assert (median (ones(0,1,0,1), 4), NaN(0,1,0));
+%!assert (median ([]), NaN)
+%!assert (median (ones(1,0)), NaN)
+%!assert (median (ones(0,1)), NaN)
+%!assert (median ([], 1), NaN(1,0))
+%!assert (median ([], 2), NaN(0,1))
+%!assert (median ([], 3), NaN(0,0))
+%!assert (median (ones(1,0), 1), NaN(1,0))
+%!assert (median (ones(1,0), 2), NaN(1,1))
+%!assert (median (ones(1,0), 3), NaN(1,0))
+%!assert (median (ones(0,1), 1), NaN(1,1))
+%!assert (median (ones(0,1), 2), NaN(0,1))
+%!assert (median (ones(0,1), 3), NaN(0,1))
+%!assert (median (ones(0,1,0,1), 1), NaN(1,1,0))
+%!assert (median (ones(0,1,0,1), 2), NaN(0,1,0))
+%!assert (median (ones(0,1,0,1), 3), NaN(0,1,1))
+%!assert (median (ones(0,1,0,1), 4), NaN(0,1,0))
 
 ## Test complex inputs (should sort by abs(a))
 %!assert (median([1 3 3i 2 1i]), 2)
@@ -685,9 +672,9 @@
 %!  intmax("uint64")-1)
 
 ## Test input case insensitivity
-%!assert (median ([1 2 3], "aLL"), 2);
-%!assert (median ([1 2 3], "OmitNan"), 2);
-%!assert (median ([1 2 3], "DOUBle"), 2);
+%!assert (median ([1 2 3], "aLL"), 2)
+%!assert (median ([1 2 3], "OmitNan"), 2)
+%!assert (median ([1 2 3], "DOUBle"), 2)
 
 ## Test input validation
 %!error <Invalid call> median ()
--- a/scripts/statistics/std.m	Wed Mar 01 12:40:50 2023 -0500
+++ b/scripts/statistics/std.m	Wed Mar 01 19:46:20 2023 -0800
@@ -59,8 +59,8 @@
 ##
 ## @table @asis
 ## @item 0 [default]:
-## Normalize with @math{N-1} (population standard deviation).  This provides the
-## square root of the best unbiased estimator of the standard deviation.
+## Normalize with @math{N-1} (population standard deviation).  This provides
+## the square root of the best unbiased estimator of the standard deviation.
 ##
 ## @item 1:
 ## Normalize with @math{N} (sample standard deviation).  This provides the
@@ -75,13 +75,13 @@
 ##
 ## @item an array:
 ## Similar to vector weights, but @var{w} must be the same size as @var{x}.  If
-## the operating dimension is supplied as @var{vecdim} or "all" and @var{w} is
-## not a scalar, @var{w} must be an same-sized array.
+## the operating dimension is supplied as @var{vecdim} or @qcode{"all"} and
+## @var{w} is not a scalar, @var{w} must be an same-sized array.
 ## @end table
 ##
-## Note: @var{w} must always be specified before specifying any of the following
-## dimension options. To use the default value for @var{w} you may pass an empty
-## input argument [].
+## Note: @var{w} must always be specified before specifying any of the
+## following dimension options.  To use the default value for @var{w} you
+## may pass an empty input argument [].
 ##
 ## The optional variable @var{dim} forces @code{std} to operate over the
 ## specified dimension, which must be a positive integer-valued number.
@@ -90,21 +90,23 @@
 ##
 ## Specifying the dimensions as  @var{vecdim}, a vector of non-repeating
 ## dimensions, will return the standard deviation calculated over the array
-## slice defined by @var{vecdim}. If @var{vecdim} indexes all dimensions of
-## @var{x}, then it is equivalent to the option @qcode{"all"}. Any dimension in
-## @var{vecdim} greater than @code{ndims (@var{x})} is ignored.
+## slice defined by @var{vecdim}.  If @var{vecdim} indexes all dimensions of
+## @var{x}, then it is equivalent to the option @qcode{"all"}.  Any
+## dimension in @var{vecdim} greater than @code{ndims (@var{x})} is ignored.
 ##
-## Specifying the dimension as @qcode{"all"} will force @code{std} to operate on
-## all elements of @var{x}, and is equivalent to @code{std (@var{x}(:))}.
+## Specifying the dimension as @qcode{"all"} will force @code{std} to
+## operate on all elements of @var{x}, and is equivalent to
+## @code{std (@var{x}(:))}.
 ##
 ## The optional variable @var{nanflag} specifies whether to include or exclude
 ## NaN values from the calculation using any of the previously specified input
-## argument combinations.  The default value for @var{nanflag} is "includenan"
-## which keeps NaN values in the calculation. To exclude NaN values set the
-## value of @var{nanflag} to "omitnan".  The output will still contain NaN
-## values if @var{x} consists of all NaN values in the operating dimension.
+## argument combinations.  The default value for @var{nanflag} is
+## @qcode{"includenan"} which keeps NaN values in the calculation.  To
+## exclude NaN values set the value of @var{nanflag} to @qcode{"omitnan"}. 
+## The output will still contain NaN values if @var{x} consists of all NaN
+## values in the operating dimension.
 ##
-## The optional second output variable @var{mu} contains the mean of the
+## The optional second output variable @var{m} contains the mean of the
 ## elements of @var{x} used to calculate the standard deviation.  If @var{v} is
 ## the weighted standard deviation, then @var{m} is also the weighted mean.
 ##
--- a/scripts/statistics/var.m	Wed Mar 01 12:40:50 2023 -0500
+++ b/scripts/statistics/var.m	Wed Mar 01 19:46:20 2023 -0800
@@ -1,6 +1,6 @@
 ########################################################################
 ##
-## Copyright (C) 1996-2023 The Octave Project Developers
+## Copyright (C) 1995-2023 The Octave Project Developers
 ##
 ## See the file COPYRIGHT.md in the top-level directory of this
 ## distribution or <https://octave.org/copyright/>.
@@ -28,7 +28,7 @@
 ## @deftypefnx {} {@var{v} =} var (@var{x}, @var{w})
 ## @deftypefnx {} {@var{v} =} var (@var{x}, @var{w}, @var{dim})
 ## @deftypefnx {} {@var{v} =} var (@var{x}, @var{w}, @var{vecdim})
-## @deftypefnx {} {@var{v} =} var (@var{x}, @var{w}, @qcode{"ALL"})
+## @deftypefnx {} {@var{v} =} var (@var{x}, @var{w}, @qcode{"all"})
 ## @deftypefnx {} {@var{v} =} var (@dots{}, @var{nanflag})
 ## @deftypefnx {} {[@var{v}, @var{m}] =} var (@dots{})
 ## Compute the variance of the elements of the vector @var{x}.
@@ -74,13 +74,13 @@
 ##
 ## @item an array:
 ## Similar to vector weights, but @var{w} must be the same size as @var{x}.  If
-## the operating dimension is supplied as @var{vecdim} or "all" and @var{w} is
-## not a scalar, @var{w} must be an same-sized array.
+## the operating dimension is supplied as @var{vecdim} or @qcode{"all"} and
+## @var{w} is not a scalar, @var{w} must be an same-sized array.
 ## @end table
 ##
-## Note: @var{w} must always be specified before specifying any of the following
-## dimension options. To use the default value for @var{w} you may pass an empty
-## input argument [].
+## Note: @var{w} must always be specified before specifying any of the
+## following dimension options.  To use the default value for @var{w} you
+## may pass an empty input argument [].
 ##
 ## The optional variable @var{dim} forces @code{var} to operate over the
 ## specified dimension, which must be a positive integer-valued number.
@@ -89,21 +89,23 @@
 ##
 ## Specifying the dimensions as  @var{vecdim}, a vector of non-repeating
 ## dimensions, will return the variance calculated over the array slice defined
-## by @var{vecdim}. If @var{vecdim} indexes all dimensions of @var{x}, then it
-## is equivalent to the option @qcode{"all"}. Any dimension in @var{vecdim}
+## by @var{vecdim}.  If @var{vecdim} indexes all dimensions of @var{x}, then it
+## is equivalent to the option @qcode{"all"}.  Any dimension in @var{vecdim}
 ## greater than @code{ndims (@var{x})} is ignored.
 ##
-## Specifying the dimension as @qcode{"all"} will force @code{var} to operate on
-## all elements of @var{x}, and is equivalent to @code{var (@var{x}(:))}.
+## Specifying the dimension as @qcode{"all"} will force @code{var} to
+## operate on all elements of @var{x}, and is equivalent to @code{var
+## (@var{x}(:))}.
 ##
 ## The optional variable @var{nanflag} specifies whether to include or exclude
 ## NaN values from the calculation using any of the previously specified input
-## argument combinations.  The default value for @var{nanflag} is "includenan"
-## which keeps NaN values in the calculation. To exclude NaN values set the
-## value of @var{nanflag} to "omitnan".  The output will still contain NaN
-## values if @var{x} consists of all NaN values in the operating dimension.
+## argument combinations.  The default value for @var{nanflag} is
+## @qcode{"includenan"} which keeps NaN values in the calculation.  To
+## exclude NaN values set the value of @var{nanflag} to @qcode{"omitnan"}. 
+## The output will still contain NaN values if @var{x} consists of all NaN
+## values in the operating dimension.
 ##
-## The optional second output variable @var{mu} contains the mean of the
+## The optional second output variable @var{m} contains the mean of the
 ## elements of @var{x} used to calculate the variance.  If @var{v} is the
 ## weighted variance, then @var{m} is also the weighted mean.
 ##
@@ -128,8 +130,8 @@
   endif
 
   if (any (varg_chars))
-    for i = varargin(varg_chars)
-      switch (lower (i{:}))
+    for argin = varargin(varg_chars)
+      switch (lower (argin{1}))
         case "all"
           all_flag = true;
         case "omitnan"
@@ -144,8 +146,8 @@
     nvarg = numel (varargin);
   endif
 
-  # FIXME: when sparse can use broadcast ops, remove sparse checks and hacks
-  sprs_x = issparse (x);
+  ## FIXME: When sparse can broadcast ops then remove sparse checks and hacks.
+  x_issparse = issparse (x);
   w = 0;
   weighted = false; # true if weight vector/array used
   vecdim = [];
@@ -156,7 +158,7 @@
 
   ## Check numeric arguments
   if (! (isnumeric (x)))
-    error ("var: X must be a numeric vector or matrix.");
+    error ("var: X must be a numeric vector or matrix");
   endif
   if (isa (x, "single"))
     outtype = "single";
@@ -170,12 +172,12 @@
     endif
     ## Process weight input
     if (any (varargin{1} < 0))
-      error ("var: weights must not contain any negative values.");
+      error ("var: weights must not contain any negative values");
     endif
     if (isscalar (varargin{1}))
       w = varargin{1};
       if (! (w == 0 || w == 1) && ! isscalar (x))
-        error ("var: normalization scalar must be either 0 or 1.");
+        error ("var: normalization scalar must be either 0 or 1");
       endif
     elseif (numel (varargin{1}) > 1)
       weights = varargin{1};
@@ -188,9 +190,9 @@
         ## Check for empty vecdim, won't change vsv if nonzero size empty
         vecdim_scalar_vector = [isscalar(vecdim), isvector(vecdim)];
       endif
-      if (! (vecdim_scalar_vector(2) && all (vecdim > 0)) ...
-             || any (rem (vecdim, 1)))
-        error ("var: DIM must be a positive integer scalar or vector.");
+      if (! (vecdim_scalar_vector(2) && all (vecdim > 0))
+          || any (rem (vecdim, 1)))
+        error ("var: DIM must be a positive integer scalar or vector");
       endif
       if (vecdim_scalar_vector(1) && vecdim > ndx && ! isempty (x))
         ## Scalar dimension larger than ndims(x), variance of any single number
@@ -202,56 +204,52 @@
         return;
       endif
       if (vecdim_scalar_vector == [0 1] && (! all (diff (sort (vecdim)))))
-        error ("var: VECDIM must contain non-repeating positive integers.");
+        error ("var: VECDIM must contain non-repeating positive integers");
       endif
     endif
   endif
 
   ## Check for conflicting input arguments
   if (all_flag && ! vecempty)
-    error ("var: 'all' flag cannot be used with DIM or VECDIM options.");
+    error ("var: 'all' flag cannot be used with DIM or VECDIM options");
   endif
   if (weighted)
     if (all_flag)
       if (isvector (weights))
         if (numel (weights) != numel (x))
-          error ("var: weight vector element count does not match X.");
+          error ("var: weight vector element count does not match X");
         endif
       elseif (! (isequal (size (weights), szx)))
-        error ("var: weight matrix or array does not match X in size.");
+        error ("var: weight matrix or array does not match X in size");
       endif
 
     elseif (vecempty)
-      dim = find (szx > 1, 1);
-      if length (dim) == 0
-        dim = 1;
-      endif
+      ## Find the first non-singleton dimension.
+      (dim = find (szx > 1, 1)) || (dim = 1);
       if (isvector (weights))
         if (numel (weights) != szx(dim))
-          error (["var: weight vector length does not match operating ", ...
-                  "dimension."]);
+          error ("var: weight vector length does not match operating dimension");
         endif
       elseif (! isequal (size (weights), szx))
-          error ("var: weight matrix or array does not match X in size.");
+          error ("var: weight matrix or array does not match X in size");
       endif
     elseif (vecdim_scalar_vector(1))
       if (isvector (weights))
         if (numel (weights) != szx(vecdim))
-          error (["var: weight vector length does not match operating ", ...
-                  "dimension."]);
+          error ("var: weight vector length does not match operating dimension");
         endif
       elseif (! isequal (size (weights), szx))
-          error ("var: weight matrix or array does not match X in size.");
+          error ("var: weight matrix or array does not match X in size");
       endif
 
     elseif (vecdim_scalar_vector(2) && ! (isequal (size (weights), szx)))
-      error ("var: weight matrix or array does not match X in size.");
+      error ("var: weight matrix or array does not match X in size");
     endif
   endif
 
-  ## Force output for X being empty or scalar
+  ## Handle special cases of empty or scalar X and exit early.
   if (isempty (x))
-    if (vecempty && (ndx == 2 || all ((szx) == 0)))
+    if (vecempty && (ndx == 2 || all (szx == 0)))
       v = NaN (outtype);
       if (nargout > 1)
         m = NaN (outtype);
@@ -266,9 +264,7 @@
       endif
       return;
     endif
-  endif
-
-  if (isscalar (x))
+  elseif (isscalar (x))
     if (isfinite (x))
       v = zeros (outtype);
     else
@@ -294,10 +290,8 @@
         v = 0;
       endif
     else
-      dim = find (szx > 1, 1);
-      if length (dim) == 0
-        dim = 1;
-      endif
+      ## Find the first non-singleton dimension.
+      (dim = find (szx > 1, 1)) || (dim = 1);
       n = szx(dim);
       if (omitnan)
         n = sum (! isnan (x), dim);
@@ -307,7 +301,7 @@
       m = sum (x, dim) ./ n;
       dims = ones (1, ndx);
       dims(dim) = szx(dim);
-      if (sprs_x)
+      if (x_issparse)
         m_exp = repmat (m, dims);
       else
         m_exp = m .* ones (dims);
@@ -317,7 +311,7 @@
       endif
       v = sumsq (x - m_exp, dim) ./ (n - 1 + w);
       if (numel (n) == 1)
-        divby0 = n .* ones (size (v)) == 1;
+        divby0 = (n .* ones (size (v))) == 1;
       else
         divby0 = n == 1;
       endif
@@ -354,10 +348,8 @@
       endif
 
     else
-      dim = find (szx > 1, 1);
-      if length (dim) == 0
-        dim = 1;
-      endif
+      ## Find the first non-singleton dimension.
+      (dim = find (szx > 1, 1)) || (dim = 1);
       if (! weighted)
         weights = ones (szx);
         wx = x;
@@ -379,7 +371,7 @@
       m = sum (wx, dim) ./ sum (weights, dim);
       dims = ones (1, ndims (wx));
       dims(dim) = size (wx, dim);
-      if (sprs_x)
+      if (x_issparse)
         m_exp = repmat (m, dims);
       else
         m_exp = m .* ones (dims);
@@ -392,7 +384,7 @@
       else
         v = sumsq (x - m_exp, dim) ./ (n - 1 + w);
         if (numel (n) == 1)
-          divby0 = n .* ones (size (v)) == 1;
+          divby0 = (n .* ones (size (v))) == 1;
         else
           divby0 = n == 1;
         endif
@@ -403,7 +395,7 @@
   elseif (nvarg == 2)
     ## Three numeric input arguments, both w or weights and dim or vecdim given.
     if (vecdim_scalar_vector(1))
-      if (!weighted)
+      if (! weighted)
         weights = ones (szx);
         wx = x;
       else
@@ -424,7 +416,7 @@
       m = sum (wx, vecdim) ./ sum (weights, vecdim);
       dims = ones (1, ndims (wx));
       dims(vecdim) = size (wx, vecdim);
-      if (sprs_x)
+      if (x_issparse)
         m_exp = repmat (m, dims);
       else
         m_exp = m .* ones (dims);
@@ -440,7 +432,7 @@
         vn = isnan (v);
         v = v ./ (n - 1 + w);
         if (numel (n) == 1)
-          divby0 = n .* ones (size (v)) == 1;
+          divby0 = (n .* ones (size (v))) == 1;
         else
           divby0 = n == 1;
         endif
@@ -451,14 +443,14 @@
     else
       ## Weights and nonscalar vecdim specified
 
-      ## Ignore exceeding dimensions in VECDIM
-      remdims = 1 : ndx;    # all dimensions
-      vecdim(find (vecdim > ndx)) = [];
+      ## Ignore dimensions in VECDIM larger than actual array.
+      remdims = 1 : ndx;    # All dimensions
+      vecdim(vecdim > ndx) = [];
       ## Calculate permutation vector
-      remdims(vecdim) = [];     # delete dimensions specified by vecdim
+      remdims(vecdim) = [];     # Delete dimensions specified by vecdim
       nremd = numel (remdims);
 
-      ## If all dimensions are given, it is similar to all flag
+      ## If all dimensions are given, it is equivalent to the 'all' flag.
       if (nremd == 0)
         x = x(:);
         if (weighted)
@@ -488,7 +480,7 @@
 
       else
 
-        ## FIXME: much of the reshaping can be skipped once octave's sum can
+        ## FIXME: much of the reshaping can be skipped once Octave's sum can
         ##        take a vecdim argument.
 
         ## Apply weights
@@ -499,20 +491,20 @@
           wx = x;
         endif
 
-        ## Permute to bring remaining dims forward
+        ## Permute to push vecdims to back
         perm = [remdims, vecdim];
         wx = permute (wx, perm);
         weights = permute (weights, perm);
         x = permute (x, perm);
 
-        ## Reshape to put all vecdims in final dimension
+        ## Reshape to squash all vecdims in final dimension
         szwx = size (wx);
         sznew = [szwx(1:nremd), prod(szwx(nremd+1:end))];
         wx = reshape (wx, sznew);
         weights = reshape (weights, sznew);
         x = reshape (x, sznew);
 
-        ## Calculate var on single, squashed dimension
+        ## Calculate var on final squashed dimension
         dim = nremd + 1;
         n = size (wx, dim);
         if (omitnan)
@@ -549,13 +541,13 @@
 
   ## Preserve class type
   if (nargout < 2)
-    if strcmp (outtype, "single")
+    if (strcmp (outtype, "single"))
       v = single (v);
     else
       v = double (v);
     endif
   else
-    if strcmp (outtype, "single")
+    if (strcmp (outtype, "single"))
       v = single (v);
       m = single (m);
     else
@@ -563,6 +555,7 @@
       m = double (m);
     endif
   endif
+
 endfunction
 
 
@@ -633,9 +626,9 @@
 %! assert (var (16*x, w, [1:3], 'omitnan'), 6519);
 
 ## Test input case insensitivity
-%!assert (var ([1 2 3], "aLl"), 1);
-%!assert (var ([1 2 3], "OmitNan"), 1);
-%!assert (var ([1 2 3], "IncludeNan"), 1);
+%!assert (var ([1 2 3], "aLl"), 1)
+%!assert (var ([1 2 3], "OmitNan"), 1)
+%!assert (var ([1 2 3], "IncludeNan"), 1)
 
 ## Test dimension indexing with vecdim in n-dimensional arrays
 %!test
@@ -681,16 +674,16 @@
 %! assert (var (x, [], [3, 2], "omitnan"), v, 4e-14);
 
 ## Testing weights vector & arrays
-%!assert (var (ones (2,2,2), [1:2], 3), [(zeros (2, 2))]);
-%!assert (var (magic (3), [1:9], "all"), 6.666666666666667, 1e-14);
+%!assert (var (ones (2,2,2), [1:2], 3), [(zeros (2, 2))])
+%!assert (var (magic (3), [1:9], "all"), 6.666666666666667, 1e-14)
 
 ## Test exceeding dimensions
-%!assert (var (ones (2,2), [], 3), zeros (2,2));
-%!assert (var (ones (2,2,2), [], 99), zeros (2,2,2));
-%!assert (var (magic (3), [], 3), zeros (3,3));
-%!assert (var (magic (3), [], 1), [7, 16, 7]);
-%!assert (var (magic (3), [], [1 3]), [7, 16, 7]);
-%!assert (var (magic (3), [], [1 99]), [7, 16, 7]);
+%!assert (var (ones (2,2), [], 3), zeros (2,2))
+%!assert (var (ones (2,2,2), [], 99), zeros (2,2,2))
+%!assert (var (magic (3), [], 3), zeros (3,3))
+%!assert (var (magic (3), [], 1), [7, 16, 7])
+%!assert (var (magic (3), [], [1 3]), [7, 16, 7])
+%!assert (var (magic (3), [], [1 99]), [7, 16, 7])
 
 ## Test empty inputs
 %!assert (var ([]), NaN)
@@ -911,7 +904,6 @@
 %! assert (issparse (v));
 %! assert (issparse (m));
 
-
 ## Test input validation
 %!error <Invalid call> var ()
 %!error <Invalid call> var (1, 2, "omitnan", 3)