Go to the RMD, PDF, or HTML version of this file. Go back to Python Code Examples Repository (bookdown site) or the pyfan Package (API).
Generate an example matlab script file with parameter x.
# Example Matlab Function
stf_m_contents = """\
a = x + 1
b = 10*x\
"""
# Print
print(stf_m_contents)
# Open new file
## a = x + 1
## b = 10*x
fl_m_contents = open("_m/fs_test.m", 'w')
# Write to File
fl_m_contents.write(stf_m_contents)
# print
## 18
fl_m_contents.close()
First, check where matlab is installed:
import subprocess
cmd_popen = subprocess.Popen(["where", "matlab"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, err = cmd_popen.communicate()
print(output.decode('utf-8'))
## G:\ProgramData\MATLAB\R2020b\bin\matlab.exe
Second, run the matlab file, first definet he parameter x:
import os
# print and set directory
print(os.getcwd())
## G:\repos\Py4Econ\support\system
os.chdir('_m')
print(os.getcwd())
# run matlab script saved prior
# running command line: matlab -batch "fs_test; exit"
## G:\repos\Py4Econ\support\system\_m
cmd_popen = subprocess.Popen(["matlab", "-batch", "\"x=1; fs_test; exit\""],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, err = cmd_popen.communicate()
print(output.decode('utf-8'))
##
## a =
##
## 2
##
##
## b =
##
## 10
##
Third, run the function again, but with x=3:
os.chdir('_m')
print(os.getcwd())
## G:\repos\Py4Econ\support\system\_m
print(subprocess.Popen(["matlab", "-batch", "\"x=5; fs_test; exit\""],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0].decode('utf-8'))
##
## a =
##
## 6
##
##
## b =
##
## 50
##