Octave plot from Qt C++ application - c++

I have a QT C++ application that runs the Octave program using QProcess. I am able to communicate with it by reading the standard output/error and writing to it's standard input using write method (for example: octave->write("5 + 5\n");).
As I told you I get response from octave (from the above example I get "ans = 10").
However, when the command I write to Octave standard input has a "plot" (for example, a simple plot([1 2 3 4 5]);), the actual graphic is never shown. I know Octave runs gnuplot, I have it installed, and gnuplot_x11 too. I even change the gnuplot binary path in my Octave process by executing gnuplot_binary("/usr/bin/gnuplot"); from MY APPLICATION. I know it runs good because if I retrieve the new value I get it right. But I don't know why Octave doesn't show the graphic.
Here I start octave:
QStringList arguments;
arguments << "--persist";
octave->setProcessChannelMode(QProcess::MergedChannels);
octave->start("/usr/bin/octave", arguments);
Here I write commands to octave process:
if (octave->state() == QProcess::Running) {
QString command = widget.txtInput->toPlainText();
if (command.isEmpty()) {
return;
}
command += "\n";
octave->write(command.toAscii());
}
With this I print the octave response to a text edit:
widget.txtOutput->append(octave->readAll() + "\n");
And finally, I use this when the octave process starts:
QString gnuplot_path(tr("\"/usr/bin/gnuplot\""));
QString gnuplot_cmd(tr("gnuplot_binary(%1)\n").arg(gnuplot_path));
octave->write(gnuplot_cmd.toAscii());
I will appreciate any help you could give me.
Thanks in advance.

Octave, like Matlab, can be run in batch mode to perform computations without graphical UI. I assume that Octave detects that it is not run from an interactive session, and therefore automatically goes into batch mode. You would expect Octave to suppress graphical output (e.g. gnuplot output) when being in batch mode.
Try to force Octave into interactive mode by using the --interactive command line option:
http://www.gnu.org/software/octave/doc/interpreter/Command-Line-Options.html

I know you probably already solved your problem but this might be helpful for other...
You can try to add a command to save your plot in a temporary folder in your octave request.
Then display the graph in your ap

Related

Plot values in .m file from C++

I have looked extensively in the net, yet not found exactly what I want.
I have a big simulation program that outputs results in a MATLAB M-file (let's call it res.m) and I want to plot the results visually.
I want to start the simulation with C++ many times in a row and therefore want to automatize the plotting of the results.
I come up to two options:
Execute from C++ an Octave or MATLAB script that generates the graph.
-> Haven't found anyone who managed to do so
Use the Octave source files to read the res.m file and output them after with whatever plotting C++ tool.
-> Theoretically possible but I get lost in those files
Is someone able to solve this? Or has a better, easier approach?
The answer is to execute through the terminal.
I didn't manage to actually run a octave script from my c++ program directly, but there is a way around messing with/through the terminal and a extra Octave file. I used in my cpp:
string = "octave myProgr.m"
const char *command = str.c_str();
system(command);
myProgr.m is the script that plots the res.m file

Matlab system() running C++ Executable

I'm having some trouble getting Matlab to run an executable file. Essentially, I have a C++ code that does some calculations and outputs these calculations to a text file; then, Matlab reads these text files and uses the calculations to makes plots and stuff.
I've been trying to get Matlab to run the C++ exe file so that, when it runs it, the output files are automatically generated and Matlab can start doing its stuff. This just allows the user to run the program quicker. I am using the system() command Like so:
system('MyCppProgram.exe');
However, when I run that, although everything compiles, nothing is outputted from CPP and I even get back something that says "ans = -1" and I have no idea what that means.
Any help would be greatly appreciated. Thank you!
Update: Result from test command.
[status, cmdout] = system('MyCppProgram.exe', '-echo');
status = -1
cmdout = ''

Initialize Octave process inside C++ program and write commands to the standered input

I'm working on a C++ project and I need to initialize a octave process inside my program and write octave commands into octave standard input and get results from octave standard output and standard error.
I searched and found that octave forge engine package do that job. But I couldn't find how to use that package. I just want to execute simple command such as 5+5 and get the answer.
Is there any way of doing this using octave engine package or using any other way.
First I created a QProcess using Qt.
QStringList arguments;
arguments << "--persist"; //set arguments of the octave process. --persist:Go interactive after
octave.setProcessChannelMode(QProcess::MergedChannels); //set process channel
octave.start("/usr/bin/octave", arguments);//If octave has installed into any other directory this should be changed.
After that I was able to write to the standered input of the octave process.
if(octave.state()==QProcess::Starting){
octave.waitForStarted();
//TODO:should set a timeout and if timeout happens set a error report.
processWrite(command);
}
else if(octave.state()==QProcess::Running){
//TODO write Code
octave.waitForReadyRead(1000);//wait until Standered output ready
if(command.isEmpty()){
return;
}
else{
command+="\n";
octave.write(command.toUtf8());
}
}
else{
//TODO: Error reporting
}

how to run plot of R into C/C++?

How do I execute a R command in C, without using R extensions, something like:
int main() {
system("R g<- graph(c(0,1,0,4,0,9,1,7,1,9,2,9,2,3,2,5,3,6,3,9,4,5,4,8,5,8,6,7,6,8,7,8),n=10,dir=FALSE)
plot(g)")
return(0)
}
You can run R using the system() call as you have, but you can't stick R functions on the command line like that.
What you can do is to write the R code to a file and call it with system("R CMD BATCH foo.R") - minimally:
main(){system("R CMD BATCH test.R");}
Now, by default the output graphics from R CMD BATCH go to a PDF file, so you need to open a graphics window and make the script pause if you want to see it.
Of course your test.R file could be written by your C code before it runs it, and you could keep it in a temporary directory or something.
An alternative for R CMD BATCH is Rscript. I think for problems where C++ and R are not tightly integrated, i.e. there are distinct phases where R and C++ are used, nor large volumes or frequency of data exchange, using system calls can be very simple and robust.
An alternative is to run R and C++ alongside each other and exchange info between them. This can be done using the RInside pacakge, which is available on CRAN.

C++ and gnuplot

This is my first post and I'm quite a novice on C++ and compiling in general.
I'm compiling a program which requires some graphs to be drawn. The program create a .dat file and then i should open gnuplot and write plot '.dat'. That's fine.
Is there a way to make gnuplot automatically open and show me the plot I need? I should use some system() function in the code to call gnuplot but how can I make him plot what I need?
Sorry for my non-perfect English :s
Thanks for the attention anyway!
Depending on your OS, you might be able to use popen(). This would let you spawn a gnuplot process and just just write to it like any other FILE*.
If you have datapoints to plot, you can pass them inline with the plot "-" ... option. Similarly, you may want to explore set data style points/lines/linespoints/etc options.
Without pause or persist, gnuplot will terminate upon end-of-input-stream. In your example case, that would be when the end of the file is reached.
To produce (write) an output file (graph), use:
set terminal png small
set output "filename.png"
There's lots of options to set terminal. Png is usually there. If not, perhaps gif, tiff, or jpeg?
Watch out for overwriting the file!
You may want to use set size 2,2 to make a larger graph. Some set terminal variants also allow you to specify the size.
I'm learning this today too. Here is a small example I cooked up.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv) {
ofstream file("data.dat");
file << "#x y" << endl;
for(int i=0; i<10; i++){
file << i << ' ' << i*i << endl;
}
file.close();
return 0;
}
Save that as plot.cpp and compile that with g++:
g++ plot.cpp -o plot
Run the program to create the .dat file:
./plot
Save the following gnuplot script as plot.plt:
set terminal svg enhanced size 1000 1000 fname "Times" fsize 36
set output "plot.svg"
set title "A simple plot of x^2 vs. x"
set xlabel "x"
set ylabel "y"
plot "./data.dat" using 1:2 title ""
Run the script with gnuplot to generate your .svg file:
gnuplot plot.plt
The resulting plot will be in plot.svg. If you leave out the first couple lines that specify the output, it will render in a window. Have fun!
Sometimes it is as easy as one may think
gnuplot file
where file is neither your data nor your result file, but a file with the command you would type in the commandline. Just enter there your commands you need (either constant file you have or generate it).
After executing all commands in that file gnuplot exits.
Yes you can. You can make a file that has the commands you would otherwise type in to set up the plot and open gnuplot running from that file. This link has an article that explains how to do it. You can also output to an EPS or other graphical output formats and display the plot using another widget that reads in the file.
You may need to use the '-persist' flag to the command. I know that on *nix systems, this flag is required if you want the plot window to remain after the gnuplot process has completed and exited.
gnuplot -persist commands.gp
Also, you can put as many gnuplot commands as you like in the file. The file acts sort of like a batch script in this regard.
You might need to add a line
pause -1
This will show the plot until return has been pressed.
What you are probably seeing is that gnuplot runs and exits before the plot has time to be displayed.
You might need to set a terminal type. Read the gnuplot documentation about that.