3

MATLAB opens a new session every time system is called. I want to be able to keep the session open and perform several calls to it.

Ideally, this would work:

system('export DUMMY=2');
[~, out] = system('echo $DUMMY');
disp(out)

But it doesn't as each system call is separate. How can I get around this and keep one session running?

The code above can be fixed by using setenv, replacing the first line with setenv('DUMMY', '2');, but I am looking for a more general solution.

buzjwa
  • 2,632
  • 2
  • 24
  • 37
  • 2
    Don't know much about Matlab but this sounds like a classic use case for `popen()` where you would open a shell (e.g. `bash`) and write commands to it.... https://www.mathworks.com/matlabcentral/fileexchange/13851-popen-read-and-write?focused=5087638&tab=example – Mark Setchell Oct 01 '17 at 08:54
  • Possible duplicate of [Average of subgroup of 2nd column, grouped by 1st column](https://stackoverflow.com/questions/33886945/average-of-subgroup-of-2nd-column-grouped-by-1st-column) – brainkz Oct 02 '17 at 22:24

1 Answers1

1

Would something along these lines be suitable for you?

C:\Users\...>SET "foo=bar" & ECHO %foo%
bar

Windows batch files and command prompt allow to execute multiple commands on a single line concatenating them with &. Example with Matlab:

[~, out] = system('SET "foo=bar" & ECHO %foo%');
disp(out); % bar

Alternatively, you could create a .bat file to be called through the system function, whose behavior depends on the arguments you pass to it (read this post for more information).

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
  • My solution is indeed running a bash script from a file (on Unix, not Windows), but this means code in the script must run more than once. For an `export` command this is not an issue. For more tasking commands it can be. – buzjwa Jan 03 '18 at 10:52