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]:
%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 = %octave [1 2; 3 4];
x
Out[2]:
array([[ 1.,  2.],
       [ 3.,  4.]])
In [4]:
a = [1, 2, 3]

%octave_push a
%octave a = a * 2;
%octave_pull a
a
Out[4]:
array([[2, 4, 6]])

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.

In [5]:
%%octave -i x -o y
y = x + 3;
In [6]:
y
Out[6]:
array([[ 4.,  5.],
       [ 6.,  7.]])

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 [10]:
%%octave -f svg

p = [12 -2.5 -8 -0.1 8];
x = 0:0.01:1;

polyout(p, 'x')
plot(x, polyval(p, x));
12*x^4 - 2.5*x^3 - 8*x^2 - 0.1*x^1 + 8
gnuplot Produced by GNUPLOT 4.4 patchlevel 4 6 6.5 7 7.5 8 8.5 9 9.5 0 0.2 0.4 0.6 0.8 1 Plot_1

The plot size is adjusted using the -s flag:

In [11]:
%%octave -s 500,500

# butterworth filter, order 2, cutoff pi/2 radians
b = [0.292893218813452  0.585786437626905  0.292893218813452];
a = [1  0  0.171572875253810];
freqz(b, a, 32);
gnuplot Produced by GNUPLOT 4.4 patchlevel 4 -3 -2.5 -2 -1.5 -1 -0.5 0 Plot_1 Pass band (dB) -60 -50 -40 -30 -20 -10 0 Plot_1 Stop band (dB) -200 -150 -100 -50 0 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 Plot_1 Phase (degrees)
In [12]:
%%octave -s 600,200 -f png

subplot(121);
[x, y] = meshgrid(0:0.1:3);
r = sin(x - 0.5).^2 + cos(y - 0.5).^2;
surf(x, y, r);

subplot(122);
sombrero()
Back to top