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.
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).
Related
I have a .m file, that when i run it manually (meaning already in MatLab, and then type the three lines) it runs just like it should.
What im trying to do is put those three lines into a m file and have it run instead of me having to type the lines once im in MatLab
This is the m file im trying to run its called "ABOVE2019_TF01_MatLabCommands_Test.m"
These are the three lines in it:
in_dir_list = {'/j078_8/58667_TF01_G11','/j078_8/58667_TF01_G09',};
out_dir_list = {'/j078_8/58667_TF01_G11','/j078_8/58667_TF01_G09',};
resid_process_GPS(in_dir_list,out_dir_list);
(again running those three lines within MatLab works exactly like I would expect)
So i try to run the ABOVE2019_TF01_MatLabCommands_Test.m file like this
/Applications/MATLAB_R2017a.app/bin/matlab -r "cd /volumes/promiseraid9/workspace/colleen/NewResiduals/j078_8; try, run('ABOVE2019_TF01_MatLabCommands_Test.m'); end; quit"
It doesn't error or anything it just exits out of MatLab instead of running the third line
If instead i changed the third line of the m file to just print out what in_dir_list it. The above command will print that out no problem. But the problem comes with the third line. For whatever reason the above code will not run the third line. What am i doing wrong?
You are using a try statement without catching or handling any exceptions that occur. Due to this, any errors which occur inside your script ABOVE2019_TF01_MatLabCommands_Test.m would not be returned to the command line.
You can verify this by running the following code from the command line:
try; asdfasdfalwelknwerewr_THIS_LINE_SHOULD_ERROR; end;
You should use a catch statement to handle any exceptions returned.
If you are running this from outside of the MATLAB desktop environment (which maintains a path to which to search for functions), are you sure that your functions are located within the search path? As in, is resid_process_GPS located within the folder named /j078_8?
I have a Matlab .m file that I usually run interactively. I would like to run some jobs overnight, WITHOUT re-writing the .m file to remove the interactive queries for input. I used to be able to do this with Fortran or C or VB executables by running a batch file from the OS's command line. Is this possible with Matlab? (Also, I don't have the Matlab compiler. But I can have Matlab open the whole time.)
Skeleton of Program:
Input variable1 from keyboard;
Input variable2 from keyboard;
Long calculation;
Save results to file;
Stop
But, if I make a "batch" .m file to run Program, like this:
Program
0.2
0.47
Program
1.2
2.4
then Program just sits there forever waiting for my input from the keyboard. Is there a way to run Program so that it gets its interactive inputs from the calling .m file?
What environment/operating system are you working on? You refer to a batch file which leads one to think you are working in Windows. If you are working in Linux, you can use the echo command and pipe the results into your program. For example:
#my_bash_script.sh
echo "0.2
0.47
" | Program
Perhaps you can do something similar if you are working with Windows batch files. Check out this as one resource:
https://ss64.com/nt/syntax-redirection.html
This is a workaround, not an answer, but it is too long for a comment. After researching this for a while, I don't think Matlab can do what the question requests. (Not without compiling the Matlab code into an executable.) I got around it by writing a function (call it Meta) that reads the entire "batch" file of responses and returns them as a string array. I gave Program two extra input parameters: a flag for interactive/batch running (FlagBatch), and a string for the batch filename (BatchName). If FlagBatch is 1, Program uses Meta to read BatchName and generate ResponseArray, which is used to provide responses to any requests from Program. Kludgey, but it works, with minimal reprogramming of Program. (Of course, I had to have access to Program's code, but if I'd only had an executable from someone else, then I wouldn't have had this problem in the first place!)
Another workaround. Define myinput (see below), and use that everywhere to replace input. As in my other workaround, you give Program two extra input parameters: a flag for interactive/batch running (FlagBatch), and a string for the batch filename (BatchName). Also have
if FlagBatch==1, fid=open(BatchName); end
near top of Program. This approach is nice when you have dozens of input statements scattered all over Program (and various subroutines/functions).
function A=myinput(fileID,prompt,formatSpec,sizeA)
% A=myinput(fileID,prompt,formatSpec);
% Function myinput will read from either stdin (keyboard) or from a file,
% allowing programs' inputs to be entered interactively or from a file.
% Use it instead of Matlab's built-in functions input and fscanf.
% fileID = file ID (fid) of the opened file, or 0 for keyboard input.
% prompt = the prompt string (not used for file input)
% formatSpec = string containing Matlab format spec;
% not used for keyboard input
% sizeA = size of A; basically specifies how many times to use formatSpec;
% not used for keyboard input
%
% Example Uses in Program (where fid would have been set earlier):
% NumOrcs=myinput(fid,'Enter # of orcs','%i',1);
% MapFile=myinput(fid,'Enter filename for LotR map','s',1);
% [Sgimli,Slegolas]=myinput(fid,'Strengths of Gimli and Legolas?','%g',2);
%
if fileID==0
if formatSpec=='%s'
A=input(prompt,'s');
else
A=input(prompt);
end
else
A = fscanf(fileID,formatSpec, sizeA);
end
return
I have two Matlab sessions runs parallel.
To be handy, I just change the parameters that are hard-coded into the scripts for each run.
So my question is, can I change the script when the first Matlab session is running that script? After I changed and saved that very script, will the first Matlab session run according to the original version of the script?
I have multiple scripts that call each other. Will it be more complicated in this situation?
If the answer is YES, it will appear to me that for each run, Matlab will make a ad-hoc copy of all the scripts and run that copy regardless of the hard-disk changes.
MATLAB's first step after you press "run" is to parse all the script/function's M-code and all of its dependencies into something akin to "byte code". That means that whatever MATLAB is running, is entirely in memory and thus not coupled anymore to what's in the M-file(s).
Therefore, you may indeed use another MATLAB session to change parameters in an M-file, save it, and run it in the new session, without affecting what the outcomes of the first session are.
Be sure to save or print the values of those variables though; working this way is a sure way to forget what values of those parameters belong to which session again :)
Note that this is NOT true for:
data files, or other files explicitly read during runtime
MEX files
A better workflow would be to convert those scripts into modular functions that receive configurable parameters as input, as opposed to hardcoding the values in the code.
That way you call the same function in each MATLAB session without making any changes to the M-files, only each session passes different input arguments as needed.
To learn more about how MATLAB detects changes in M-files, run the following:
>> help changeNotification
>> help changeNotificationAdvanced
You also might also wanna read about the following functions: rehash and clear functions
EDIT:
One way to find out which scripts/functions are currently "loaded in memory" is to use inmem. Say for example we have the following script saved in a file available on the path (the same works for functions):
testScript.m
x = 10;
disp(x)
Now starting with a clean session, the script is initially not loaded. After calling the script, the file is loaded and remains in memory:
% initially not loaded
>> ismember('testScript', inmem())
ans =
0
% execute script
>> testScript
10
% file is cached in memory
>> ismember('testScript', inmem())
ans =
1
Immediately continuing with the same session, make an edit to the file (for example change x to 99). By checking the list of loaded functions/scripts again, you will see that MATLAB has already detected the change, and invalidated the cached version by removing it from memory:
>> % .. make changes to testScript.m file
% file is automatically unloaded
>> ismember('testScript', inmem())
ans =
0
% execute the new script
>> testScript
99
% the result is cached once more
>> ismember('testScript', inmem())
ans =
1
I tested the above on my Windows machine, but I can't guarantee this behavior is cross-platform, you'll have to test it on Mac/Linux and see if works the same...
The script can definately be altered without influencing an ongoing run. However, if your flow gets more complicated it can be problematic to depend on what will happen:
Here are some flows you will not likely want:
main1 calls sub
sub is edited
main2 calls sub
main1 continues to run and calls sub for a second time
In the above case I would expect the second run of main1 to be calling the altered version of sub, but I would not depend on it.
main1 calls sub
sub is edited
sub called by main1 hits a breakpoint
I am not even sure what will happen, but I believe that you will stop on the original line, but will see the edited code. So the line you find may not even be the line with the breakpoint anymore.
So to conclude: Don't alter your script frequently to change the output, rather give it inputs that will determine the output.
Okay, I've searched all across this site, without any luck.
Here's my problem:
I have an .exe that produces two output files when run, which it does fine when I actually use the .exe itself.
However, when I run it in MATLAB (yes it actually runs and has identical system messages just like in the command prompt), the two output files are NOT produced. I'm not sure if this is something that can be controlled using system() in MATLAB, or this is a problem with the .exe.
My code to run the .exe (it also takes an input file) is simply this:
system(['C:\MyProgram.exe ' myInputFile]);
Any tips, pointers, advice, or solutions are greatly appreciated!!!
I assume myInputfile as a string. I guess your program is NOT running, because I'd say your command is not working. Try the following:
yourCommand = strcat('c: && MyProgram.exe',{' '},myInputFile);
system( yourCommand{1} );
{' '} is neccesary, because spaces at the end of strings are ignored.
You can not just type your path into the command line, you need to define the path before and then call the function. As you cannot put all commands in a row, you need to use &&, which is like typing Enter in the command window.
I have 'inherited' Matlab code (A) that uses another compiled Matlab code (B). I do not have the source of B. B requires user intervention ('Hit return to continue'), and I need to use A in a loop. I need to do something so I would not need to hit Return each and every time until the loop is done.
The command I use in the loop is:
str='!start "Code_B" /low "c:\Code_B\bin\Code.exe" r';
eval(str)
Are there any other switches that I can use to suppress the call to 'Hit return' ?
Thanks
Katto
One way you could do this is to create a batch file that:
Starts the compiled Matlab program
Waits for the program to run (fixed delay?)
Uses a utility to send the program an Enter key
There are many (free) utilities that let you send keystrokes to a program.
Instead of calling Program B, you would call this batch file.
You can create a text file, let's say autoreturn.txt, with many empty lines (just end of line characters), over the number of loops you expect. Then add redirection of input from this at the end of your string:
str='!start "Code_B" /low "c:\Code_B\bin\Code.exe" r < autoreturn.txt';