changeset 324:2b2460295218

pyobject.double: New method to convert numeric object to Octave double * @pyobject/pyobject.m: Add method double to convert Python numeric and array objects to Octave double scalars and arrays. Add %!tests of double value extraction.
author Mike Miller <mtmiller@octave.org>
date Fri, 12 Aug 2016 00:57:46 -0700
parents a511d43e1fc0
children fd5881d48238 778c91283a73
files @pyobject/pyobject.m
diffstat 1 files changed, 21 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/@pyobject/pyobject.m	Fri Aug 12 00:54:19 2016 -0700
+++ b/@pyobject/pyobject.m	Fri Aug 12 00:57:46 2016 -0700
@@ -129,6 +129,16 @@
       s = sprintf ("py.%s", char (s));
     endfunction
 
+    function y = double (x)
+      fn = pyeval ("lambda x: isinstance(x, __import__('array').array)");
+      if (pycall (fn, x))
+        c = cell (x);
+        y = cellfun (@(t) eval ("double (t)"), c);
+      else
+        y = pycall ("float", x);
+      endif
+    endfunction
+
     function vargout = help (x)
       idx = struct ("type", ".", "subs", "__doc__");
       s = subsref (x, idx);
@@ -308,3 +318,14 @@
 %!assert (class (pyeval ("set()")), "py.set")
 %!assert (class (pyeval ("None")), "py.NoneType")
 %!assert (class (pyeval ("2.5")), "double")
+
+## Test conversion method pyobject.double
+%!assert (double (pyobject (2.5)), 2.5)
+%!assert (double (pyobject (42)), 42)
+%!assert (double (pyobject ("42")), 42)
+%!assert (double (pyobject (false)), 0)
+%!assert (double (pycall ("array.array", "d", {31, 32, 33, 34})), [31, 32, 33, 34])
+
+%!error double (pyobject ("this is not a number"))
+%!error double (pyobject ())
+%!error double (pyeval ("[1, 2, 3]"))