Calling Matlab (2016a) function from Python(3.6)

Paul Moore p.f.moore at gmail.com
Wed Mar 28 06:10:38 EDT 2018


On 28 March 2018 at 10:23,  <rishika21sen at gmail.com> wrote:
> So I am using the following code to call a Matlab(2016a) function from python(3.6).
>
>>>import win32com.client
>>>h = win32com.client.Dispatch('matlab.application')
>>>h.Execute ("plot([0 18], [7 23])")
>
> When I am using the 'Execute' statement to run a matlab file from python, I use the statement on python:
>>>h.Execute ("run('H:\rishika\MATLAB\filewrite.m')")
>
> Now this gives the error on python:
> '??? Error: String is not terminated properly.\n\n'
>
> On the other hand, when I am running the command:
>>>run('H:\rishika\MATLAB\filewrite.m')
> on command prompt of Matlab, it is working. But when run from python, the statement isn't executing.
>
> But when I am executing
>>>h.Execute ("disp('hi')")
> on python, I am getting the proper output:
> 'hi\n'
>
> Kindly point out my mistake.

Your string in the command

> When I am using the 'Execute' statement to run a matlab file from python, I use the statement on python:
>>>h.Execute ("run('H:\rishika\MATLAB\filewrite.m')")

uses unescaped backslashes, so \r is getting seen as Carriage Return
in the string being sent to Matlab. The \f will also be seen as a form
feed. I imagine that would confuse Matlab.

You should either double the backslashes

    >>>h.Execute ("run('H:\\rishika\\MATLAB\\filewrite.m')")

or use raw strings

    >>>h.Execute ("run(r'H:\rishika\MATLAB\filewrite.m')")

Paul



More information about the Python-list mailing list