#!/usr/bin/env python # coding: utf-8 # # octavemagic: Octave inside IPython # ## Installation # The `octavemagic` extension provides the ability to interact with Octave. It is provided by the `oct2py` package, # which may be installed using `pip` or `easy_install`. # # To enable the extension, load it as follows: # In[1]: get_ipython().run_line_magic('load_ext', 'oct2py.ipython') # ## Overview # Loading the extension enables three magic functions: `%octave`, `%octave_push`, and `%octave_pull`. # # The first is for executing one or more lines of Octave, while the latter allow moving variables between the Octave and Python workspace. # Here you see an example of how to execute a single line of Octave, and how to transfer the generated value back to Python: # In[2]: x = get_ipython().run_line_magic('octave', '[1 2; 3 4];') x # In[3]: a = [1, 2, 3] get_ipython().run_line_magic('octave_push', 'a') get_ipython().run_line_magic('octave', 'a = a * 2;') get_ipython().run_line_magic('octave_pull', 'a') a # When using the cell magic, `%%octave` (note the double `%`), multiple lines of Octave can be executed together. Unlike # with the single cell magic, no value is returned, so we use the `-i` and `-o` flags to specify input and output variables. Also note the use of the semicolon to suppress the Octave output. # In[4]: get_ipython().run_cell_magic('octave', '-i x -o U,S,V', '[U, S, V] = svd(x);\n') # In[5]: print(U, S, V) # ## Plotting # Plot output is automatically captured and displayed, and using the `-f` flag you may choose its format (currently, `png` and `svg` are supported). # In[6]: get_ipython().run_cell_magic('octave', '-f svg', "\np = [12 -2.5 -8 -0.1 8];\nx = 0:0.01:1;\n\npolyout(p, 'x')\nplot(x, polyval(p, x));\n") # The width or the height can be specified to constrain the image while maintaining the original aspect ratio. # In[7]: get_ipython().run_cell_magic('octave', '-f png -w 600', '\n% butterworth filter, order 2, cutoff pi/2 radians\nb = [0.292893218813452 0.585786437626905 0.292893218813452];\na = [1 0 0.171572875253810];\nfreqz(b, a, 32);\n') # In[8]: get_ipython().run_cell_magic('octave', '-s 600,200 -f png', '\n% Note: On Windows, this will not show the plots unless Ghostscript is installed.\n\nsubplot(121);\n[x, y] = meshgrid(0:0.1:3);\nr = sin(x - 0.5).^2 + cos(y - 0.5).^2;\nsurf(x, y, r);\n\nsubplot(122);\nsombrero()\n') # Multiple figures can be drawn. Note that when using imshow the image will be created as a PNG with the raw # image dimensions. # In[9]: get_ipython().run_cell_magic('octave', '-f svg -h 300', 'sombrero\nfigure\nimshow(rand(200,200))\n')