我一直在编写一个 C++ 程序来解决简单钟摆的问题,然后使用 GNU Octave 绘制结果。它通过我程序中的这一行绘制结果:
system("./simppenadj.sh");
Run Code Online (Sandbox Code Playgroud)
在哪里simppenadj.sh:
#!/bin/sh
octave --no-gui --persist -q simppenadj.m
Run Code Online (Sandbox Code Playgroud)
并且simppenadj.m是:
#!/usr/bin/octave
# Plotting simppenadj.txt
A = importdata('simppenadj.txt');
B = importdata('simppenadjdx.txt');
t = A(:,1);
theta = A(:,2);
dtheta = B(:,2);
figure
plot(t,theta)
xlabel('t','FontSize',16,'FontWeight','bold')
ylabel('\theta','FontSize',16,'FontWeight','bold')
title('{d^{2}\theta}/{d{t^{2}}} = -9.8 cos({\theta})','FontSize',18,'FontWeight','bold')
figure
plot(theta,dtheta)
xlabel('\theta','FontSize',16,'FontWeight','bold')
ylabel('d\theta/dt','FontSize',16,'FontWeight','bold')
title('{d^{2}\theta}/{d{t^{2}}} = -9.8 cos({\theta})','FontSize',18,'FontWeight','bold')
Run Code Online (Sandbox Code Playgroud)
每当我运行我的 C++ 程序时,GNU Octave 的 CLI 就会启动(并在最后保持打开状态)并绘制数据。我不希望 GNU Octave 的 CLI 保持打开状态,但我知道如何让它不打开的唯一方法是删除--persist选项,simppenadj.sh其中也使 GNU Octave 生成的图不保持打开状态。这是一个问题,因为我希望在我的 C++ 程序运行后保持打开状态。那么有没有办法做到这一点?
您可以使用八度 API 从您的程序中调用脚本。在那里,创建一个调用八度的子进程,这样父进程就可以结束了。有了这个,你可以保持八度运行。使用此方法,没有八度 CLI,因为您通过 API 执行所有八度调用,尤其是feval.
不幸的是,使用 API 的指南非常糟糕,但我为您整理了一些应该可行的东西。它基本上只读取一个脚本并执行相应的功能。这是这种方法的好处:您可以使用普通的八度函数/脚本文件方法编写所有内容。
我printf在八度文件中添加了该语句,以展示如何将参数传递给八度。
#include <iostream>
#include <unistd.h>
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/toplev.h>
int main()
{
pid_t pid = fork();
if(pid != 0) // parent
{
std::cout << "parent, exiting\n";
}
else
{
// arguments for octave
string_vector argv (2);
argv(0) = "embedded";
argv(1) = "-q"; // quiet
// start octave, run embedded (third parameter == true)
octave_main (2, argv.c_str_vec (), true);
// read the script file
source_file("calc_and_plot.m");
// call the function with an argument
octave_value_list in;
in(0) = "Hello, world.";
feval("calc_and_plot", in);
std::cout << "octave (child process) done\n";
clean_up_and_exit(0); // quit octave. This also quits the program,
// so use this together with atexit, if you
// need to do something else after octave exits
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
function calc_and_plot(str)
printf('%s\n', str);
x = linspace(0, 2*pi, 100);
y = sin(x);
it = plot(y);
waitfor(it);
end
Run Code Online (Sandbox Code Playgroud)
编译 main.cpp
g++ main.cpp -L/usr/lib/octave-4.0.2 -I/usr/include/octave-4.0.2 -loctave -loctinterp
Run Code Online (Sandbox Code Playgroud)
您必须调整系统路径和八度音程版本。您也可以使用该mkoctfile命令,它的作用基本相同。您可以查看其-p开关的输出,例如
mkoctfile -p CFLAGS
Run Code Online (Sandbox Code Playgroud)
获取库、编译器标志等。查看相关的联机帮助页。