Matlab system() running C++ Executable - c++

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 = ''

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

C++ Write to file not working in my addition to an existing application

I have an application that collects heart rate data and displays in in a GUI. I don't want to change anything about how the application runs, but want to save the data into a .csv file to use with data manipulation programs. The program is called BluetoothGattHeartRate. I am running the sample code found here.
My addition to the code is just
std::fstream theDump;
theDump.open("path/to/file", std::fstream::out);
if (theDump.is_open())
{
theDump.write("ImHere", 6);
}
theDump.close();
inserted into the file called HeartRateService.cpp in the Shared directory in the void HeartRateService::Characteristic_ValueChanged(GattCharacteristic^ sender, GattValueChangedEventArgs^ args) function just before the call to ValueChangeCompleted(heartRateValue);. I'm using Microsoft Visual Studio to edit and run the code, as the tutorial online says. This exact code succeeds in editing the file when run in an independent application, but it fails to open the file (I tested for this) when run in the Gatt sample code.
I don't expect that anyone has dealt with this before, but if by some miracle one of you has figured this out, please let me know how you fixed it.

Executing a .bat file with a parameter and reading the console output in C++

I have a batch file I need to execute, it has one parameter, If I were to run this script myself I would open up cmd and write
lexparser.bat texfile.txt
and the output would then be printed to the console.
I have shopped around and I have found some code which seems to be executing the file but I can't seem to extract the data being output, but I am unsure if this is correct.
QString pathDocument = qApp->applicationDirPath()+ "/stanford/lexparser.bat";
long result = (long)ShellExecute(0, 0, reinterpret_cast<const WCHAR*>(pathDocument.utf16()), 0, 0, SW_NORMAL);
I am using C++ as my language and I am also using the Qt Library to help me.
I have limited programming ability so any help would be greatly appreciated
I would recommend using QProcess for doing that.
See this question and its accepted answer for an example on how to do so.

Differences when writing to / reading from the console between gfortran- and g77-compiled code

This one's going to take a bit of explaining. Please bear with me.
What I Have
I have in my possession some Fortran source code and some binaries that have been compiled from that code. I did not do the compilation, but there is a build script that suggests G77 was used to do it.
As well as the Fortran stuff, there is also some Java code that provides users with a GUI "wrapper" around the binaries. It passes information between itself and the binaries via their input/output/error pipes. The Java code is very messy, and this way of doing things adds a lot of boilerplate and redundancy, but it does the job and I know it works.
What I Need
Unfortunately, I'd like to make some changes:
I want to create a new Python wrapper for the binaries (or, more precisely, extend an existing Python program to become the new wrapper).
I want to be able to compile the Fortran code as part of this existing program's build process. I would like to use gfortran for this, since MinGW is used elsewhere in the build and so it will be readily available.
The Problem
When I compile the Fortran code myself using gfortran, I cannot get the resulting binaries to "talk" to either the current Java wrapper or my new Python wrapper.
Here are the various ways of printing to the console that I have tried in the Fortran code:
subroutine printA(message)
write(6,*) message
end
subroutine printB(message)
write(*,*) message
end
subroutine printC(message)
use iso_fortran_env
write(output_unit,*) message
end
There are also read commands as well, but the code doesn't even get a change to execute that part so I'm not worrying about it yet.
Extra Info
I have to call gfortran with the -ffixed-line-length-132 flag so that the code compiles, but apart from that I don't use anything else. I have tried using the -ff2c flag in the vague hope that it will make a difference. It doesn't.
This stackoverflow post is informative, but doesn't offer me anything that works.
The relavant manual page suggests that printA should work just fine.
I'm working on Windows, but will need this to be multi-platform.
Juse in case you're intested, the Java code uses Runtime.getRuntime().exec("prog.exe") to call the binaries and then the various "stream" methods of the resulting Process object to communicate with them. The Python code uses equivalents of this provided by the Popen object of the subprocess module.
I should also say that I am aware there are alternatives. Rewriting the code in Python (or something else like C++), or making amendments so that is it can be called via F2Py have been ruled out as options. Using g77 is also a no-go; we have enough dependencies as it is. I'd like to be able to write to / read from the console properly with gfortran, or know that it's just not possible.
Hard to say without seeing more details from your Fortran and Python codes. The following pair of code works for me (at least under Linux):
Fortran program repeating its input line by line prefixed with line number:
program test_communication
use iso_fortran_env, stdout => output_unit, stdin => input_unit
implicit none
character(100) :: buffer
integer :: ii
ii = 1
do while (.true.)
read(stdin, *) buffer
write(stdout, "(I0,A,A)") ii, "|", trim(buffer)
flush(stdout)
ii = ii + 1
end do
end program test_communication
Python program invoking the Fortran binary. You can feed it with arbitrary strings from the console.
import subprocess as sub
print "Starting child"
proc = sub.Popen("./a.out", stdin=sub.PIPE, stdout=sub.PIPE)
while True:
send = raw_input("Enter a string: ")
if not send:
print "Exiting loop"
break
proc.stdin.write(send)
proc.stdin.write("\n")
proc.stdin.flush()
print "Sent:", send
recv = proc.stdout.readline()
print "Received:", recv.rstrip()
print "Killing child"
proc.kill()

Octave plot from Qt C++ application

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