Clear Filters
Clear Filters

How to control the seed when using MATLAB engine API in Python?

9 views (last 30 days)
I am trying to call a MATLAB function from a Python script using MATLAB Engine API. In particular, the function generates a matrix of fractional Gaussian noise (fgn) using the Fraclab 2.2 toolbox (I am using "fbmwoodchan" method). When I call the function from a .m file in MATLAB, it works perfectly, producing matrices with different values on each run (given that I didn't specify any seed).
However, when I call the same function from a .py file using the MATLAB Engine API, it seems as if there is a fixed seed in Python. After each run, the generated matrix has the same values, and strangely, the first two columns are identical.
The Python code is the following (I have to change the directory since Pyhton was not able to find the Fraclab function):
eng = matlab.engine.start_matlab()
eng.cd(r"MYDIR")
eng.flpath(nargout=0)
eng.cd(os.getcwd())
eng.MYFUNCTION(INPUT1, INPUT2, INPUT3, nargout=0)
eng.quit()
I have already tried to solve the issue by adding the following line in Python:
eng.eval("rng('shuffle')", nargout=0)
immediately after defining "eng." However, the shuffle seems to works only on the first column, and all other columns remain the same after each run.
I am using MATLAB R2023b and Python 3.11 64-bit.
How can I control the seed when using the MATLAB Engine API in Python?

Answers (1)

Neha
Neha on 27 Nov 2023
Hi Gioele,
I understand that you are facing an issue while generating matrices using the "fbmwoodchan" method where the matrices exhibit fixed seed behavior. When the MATLAB Engine API is initiated in Python, the random seed is set to a default value, similar to "rng('default')". This behavior mimics the scenario when you open a new MATLAB session and call the "fbm" function.
Hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!