MATLAB: Am I getting an error that the file cannot be found when running the Simulink model with “parsim”

callbackerrorfileloadmodelParallel Computing Toolboxparsimsimsimulatesimulink

In my Simulink model, one of my model callbacks loads a file from my current directory.
load('./somefile.txt')
If I run this model using the "sim" command, my model works as expected and the file is properly loaded.
However, if I run this model using the "parsim" command, I get an error message saying my file cannot be found in my current directory. I have noticed that I can resolve this error by specifying the full path of my file instead of a relative path, but my workflow requires this argument to be passed to the "load" function as a relative path.
How can I load this file with a relative path when using "parsim"?

Best Answer

This error message is due to MATLAB changing the current directory to a temporary directory while running a Simulink model with "parsim".
For example, create a model callback that will saves the current directory at the time of simulation and also loads a file.
Run the model, comparing the current directory before simulation and during simulation. This directory has not changed, and the model simulates successfully.
Run the same model with "parsim", and notice the error message saying the file cannot be found in the current directory.
To see what the current directory gets changed to during simulation, comment out the line of the model callback that loads the file. Then, the model will run successfully using "parsim". Compare the current directory of each worker before running the simulation, and then the captured current directory while the model is running.
To resolve this error message, try one of the following workarounds:
1) Use the "<https://www.mathworks.com/help/releases/R2018a/simulink/slref/parsim.html#bvnh103-SetupFcn SetUp Fcn>" argument of "parsim" to load the file instead of a model callback. This function will act similarly to a "PreLoad Fcn" model callback, but for when the Simulink model is loaded onto each worker.
2) If your workflow requires loading the file during simulation, remove the "./" from the "load" function syntax.
load('somefile.txt.')
Using "./" tells MATLAB to only look for this file within its current folder. If you remove this, MATLAB will search its entire path, including your intended current directory.
3) If your workflow requires loading the file during simulation and including the "./" in the syntax, copy the file to be found into the temporary directory.
originalpath = which('somefile.txt')
desiredpath = fullfile(pwd,'somefile.txt')
copyfile(originalpath,pwd)
load('./somefile.txt')