MATLAB: How to detect which instance of MATLAB I am working from

multiple instances

I currently have 7 instances of MATLAB open on my PC running long simulations. They are all running the same functions with different inputs. To ensure there is no accidental interaction between instances I have temporary folders that each instance uses for data input and output before saving the final result elsewhere. I currently input an instance value (1-7) by hand for each MATLAB instance to tell them apart but can I get MATLAB to work out which instance it is automatically?

Best Answer

As far as I understand, it is not defined anywhere, what the "instance" is. Then Matlab cannot detect it automatically.
Start with defining a key to recognize the "instance". Use e.g. the PID, the process ID provided by the operating system.
Then you need e.g. a file, which contains the relation between the PID and the instance. But closing and restarting a Matlab session results in a new or old PID, such that this helps only to identify the current set of Matlab sessions.
Another option would be to create a UUID to identify a Matlab session. See e.g. or:
jUUID = java.util.UUID.randomUUID;
cUUID = char(jUUID.toString);
>> a8a4eae2-6cc7-47d3-b58e-408b71fab260
This is such random that it can be considered to be unique. Well, storing this e.g. in the ApplicationData of the groot object might be useful to identify a Matlab session securely, but you wanted a simple counter for the instance, as far as I understand.
1. What about starting the Matlab session with defining the instance number automatically:
for k = 1:7
system(sprintf('matlab -r "setappdata(groot, ''Instance'', %d)"', k)
This can be done from a bash or batch script also. Then you can request the instance easily from the code:
myInstance = getappdata(groot, 'Instance')
2. You could request, how many other Matlab instances are running already. This could be done in startup.m:
[status, str] = system('tasklist'); % Assuming Windows, use 'ps -eaf' on Linux
List = strsplit(str, '\n');
nMatlab = sum(strncmp(List, 'matlab.exe', 10));
% Now store nMatlab in groot as above
But again you get a problem, if you e.g. stop 2 Matlab sessions and open a new one. Then you have a duplicate instance number. So version 1 is more reliable.