使用批量调用运行交互式Matlab .m文件

时间:2017-06-14 22:49:12

标签: matlab batch-file

我有一个Matlab .m文件,我通常以交互方式运行。我想在一夜之间运行一些工作,而无需重新编写.m文件以删除交互式查询以进行输入。我曾经能够通过从操作系统的命令行运行批处理文件来使用Fortran或C或VB可执行文件。这可能与Matlab有关吗? (另外,我没有Matlab编译器。但是我可以让Matlab一直打开。)

计划的骷髅:

Input variable1 from keyboard; 
Input variable2 from keyboard; 
Long calculation; 
Save results to file; 
Stop

但是,如果我创建一个“批处理”.m文件来运行Program,就像这样:

Program
0.2
0.47
Program
1.2
2.4

然后程序只是坐在那里等待我从键盘输入。有没有办法运行程序,以便它从调用.m文件中获取其交互式输入?

3 个答案:

答案 0 :(得分:0)

您正在使用哪种环境/操作系统?您可以参考批处理文件,该文件会让您认为自己在Windows中工作。如果您在Linux中工作,则可以使用echo命令将结果通过管道传输到程序中。例如:

#my_bash_script.sh
echo "0.2
0.47
" | Program

如果您正在使用Windows批处理文件,也许您可​​以执行类似的操作。看看这是一个资源: https://ss64.com/nt/syntax-redirection.html

答案 1 :(得分:0)

这是一种解决方法,而非答案,但评论时间太长。经过一段时间的研究后,我不认为Matlab可以做出问题的要求。 (并非没有将Matlab代码编译成可执行文件。)我通过编写一个函数(称为Meta)来读取整个&#34;批处理&#34;响应文件并将它们作为字符串数组返回。我给了Program两个额外的输入参数:一个用于交互/批处理运行的标志(FlagBatch),以及一个用于批处理文件名(BatchName)的字符串。如果FlagBatch为1,则Program使用Meta读取BatchName并生成ResponseArray,用于提供对来自Program的任何请求的响应。 Kludgey,但它的工作原理,对程序的重新编程很少。 (当然,我必须能够访问Program的代码,但如果我只有其他人的可执行文件,那么我首先不会遇到这个问题!)< / p>

答案 2 :(得分:0)

另一种解决方法。定义myinput(见下文),并在任何地方使用它来替换输入。与我的其他解决方法一样,您为Program提供了两个额外的输入参数:交互/批处理运行的标志(FlagBatch),以及批处理文件名(BatchName)的字符串。还有

if FlagBatch==1, fid=open(BatchName); end

靠近计划的顶部。当你在程序(以及各种子程序/函数)中散布了数十个输入语句时,这种方法很不错。

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