pythonmatlaboctaveoct2py

matrix multiplication with oct2py


I am using oct2py to run octave function with python. It is working but I get an error when I try to multiply 2 matrix. What can I do to solve the problem?

this is a sample matlab funcion

%% MATLAB
function lol = jk2(arg1,arg2)
    arg1 = arg1;
    arg2 = arg2;
    lol = arg1*arg2;

end

this is the code to call the function

import oct2py
from oct2py import octave
a=3
b=4
octave.call("/MATLAB/jk2.m",a,b) # this call works
a=np.array([[1,2],[3,4]])
b=np.array([[5,6],[1,2]])
octave.call("/MATLAB/jk2.m",a,b) # this call report an errors 

This is the error message

>>> octave.call("/home/donbeo/Documents/MATLAB/jk2.m",a,b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/oct2py-1.2.0-py2.7.egg/oct2py/session.py", line 210, in call
    resp = self._eval(cmd, verbose=verbose)
  File "/usr/local/lib/python2.7/dist-packages/oct2py-1.2.0-py2.7.egg/oct2py/session.py", line 350, in _eval
    return self._session.evaluate(cmds, verbose, log, self.logger)
  File "/usr/local/lib/python2.7/dist-packages/oct2py-1.2.0-py2.7.egg/oct2py/session.py", line 523, in evaluate
    raise Oct2PyError(msg)
oct2py.utils.Oct2PyError: Oct2Py tried to run:
"""
[a__] = jk2(A__, B__)
"""
Octave returned:
binary operator '*' not implemented for 'int64 matrix' by 'int64 matrix' operations
>>> 

Solution

  • Here is an example of where the line between Python and Octave gets blurry. Numpy interprets your arrays as being of integer type (because there are no explicit floats), but Octave would treat the arrays as Doubles. If you add a period anywhere in you array definitions, it will all work.

    Fixed (tested) example:

    from oct2py import octave
    import numpy as np
    a = np.array([[1, 2], [3, 4.]])  # notice the addition of the period
    b = np.array([[5, 6], [1, 2], dtype=float])  # another way to specify floating point type
    octave.call("/MATLAB/jk2.m", a, b)  # this call works just fine