Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

call octave from sage and back

Views: 752
License: APACHE
Kernel: SageMath (default)

Call Octave from Sage and back

The code we want to run is in f1.m in the same directory

two variants below:

The data

warning make all values floats - not ints! otherwise you get that horrible implicit downcast to single vals

data = matrix(RDF, [[1.1, 2], [3.9, -1]]) data
[ 1.1 2.0] [ 3.9 -1.0]
b = 99.0 # .0 is important, not just 99

Variant A

Use Sage's octave wrapper to call function f1

octave.set('data', data) octave.set('b', b)
octave('f1(data, b)').sage()
(199.1, 200.0)

warning this looks weird ... just first line

octave.get('data')
'\n\n 1.1 2\n'
octave('data').sage()
(1.1, 2.0)

Variant B

use mat files to exchange data and use a small helper script runit.m

from scipy.io import savemat, loadmat
savemat('data.mat', {'data' : data, 'b': b})

running the driver file runit.m using octave

! octave -W runit.m

which saves the result in result.mat

result = loadmat('result.mat') y = result['y'] y
array([[199.1, 200. ], [201.9, 197. ]])
y_sage = matrix(y) y_sage
[199.1 200.0] [201.9 197.0]
type(y_sage), y_sage.parent()
(<type 'sage.matrix.matrix_real_double_dense.Matrix_real_double_dense'>, Full MatrixSpace of 2 by 2 dense matrices over Real Double Field)