matlab script to c++ - c++

I am trying to implement this person's code: http://iris.lib.neu.edu/civil_eng_theses/30/ but I can not generate a working executable in visual studio because I am missing 2 files: myoutput.cpp and PrintTimeReferencedVariable.cpp. I am unclear if the Matlab builder is supposed to generate them or I write them.
The myoutput.cpp is supposed to be a C++ file that does essentially a dlmwrite. It is used as follows:
function [] = Output_01(FileName, FileNameLenght, OutputData, OutputSize1, OutputSize2)
coder.inline('never')
coder.ceval( 'myoutput', FileName, FileNameLenght, OutputData, OutputSize1, OutputSize2);
end
% %% Matlab Version: to run the model in Matlab uncomment below, comment above
% function [] = Output_01(FileName, FileNameLenght, OutputData, OutputSize1, OutputSize2)
% dlmwrite(FileName, OutputData,'-append','coffset',0,'delimiter','\t','precision','%6.6G')
% precision = 4;
% disp( num2str( OutputData,precision))
% end
Where the commented out is the matlab version of the file and the top is what is built into C++. The files are supposed to write to the directory: C:\matlab-results-from-cpp.
The PrintTimeReferencedVariable.cpp looks like a date function that should do:
% Date = datestr(now, 'yyyy-mm-dd-HH-MM-SS' );
%% Matlab Version: to run the model in Matlab uncomment above, comment below
Date = '2012-09-16-09-19-20';
coder.ceval('PrintTimeReferencedVariable', coder.wref(Date));
Any insight into this would be much help. I'm still waiting to hear back from the author but it would still be helpful to hear all of your input as this is my first time in C++ and building projects in Matlab.
Thanks!

Seems like the text is pretty clear on what you do, though I can understand the confusion not coming from a C++ background:
5)
“Project Settings ”adjustments: Open ‘More settings’,then in ‘All Settings’ tab, choose for ‘Language’ C ++; In “Speed” tab mark only “Saturate on integer overflow”, unmark everything else; in “Custom Code ” tab, copy and paste the first lines the functions “myoutput.cpp” and “PrintTimeReferencedVariable.cpp”, followed by semicolon or see below the text:
void PrintTimeReferencedVariable (char * DateOut);
void myoutput(const char* _filename, int fileNameLen, double* data, int n, int m);
So you create the files "myoutput.cpp" and "PrintTimeReferencedVariable.cpp". Copy and paste the code into the respective cpp files. Then add the prototype(the second quote) to your header or at the top of those files.

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

GDI Print API StartDoc function is giving inconsistent results

In my application a user can have multiple documents open and print all documents to PDF's using a "Microsoft print to pdf" option when they are prompted at the print dialog window, after which they choose the destination folder. Now what happens is that if there are 30 documents selected for print, an inconsistent amount are successfully printed to pdf in the desired folder each time it is run. Sometimes all are successful and other times not. I found that files with unicode character names like this "敥敥敥敥敥敥敥敥" where being created in the same directory as the file of code that contains this print to pdf process. I can rename these files with a ".pdf" extension and they are working pdf documents.
Here is the part of code concerned:
DOCINFO docInfo;
memset(&docInfo, 0, sizeof(docInfo));
docInfo.cbSize = sizeof(docInfo);
docInfo.lpszDocName = csPlanoName;
docInfo.lpszOutput = csOutputDir + csPlanoName + csExtension;
if(dc.StartDoc(&docInfo) > 0) {
//printing process continues
}
I found that by stepping through the code, the StartDoc function call would change docInfo.lpszOutput to the same unicode characters "敥敥敥敥敥敥敥敥". This would not happen all the time, and does not happen with specific files when testing. One test a document will print to pdf successfully, another test with the same document and it will create the file with the name "敥敥敥敥敥敥敥敥".
Any help with this would be greatly appreciated.
Regards,
Chris
What are csPlanoName csOutputDir? docInfo.lpszDocName and docInfo.lpszOutput must be pointers to null-terminated strings and since you are using csOutputDir + csPlanoName + csExtension that won't work with regular pointers something else might be happening here. Make sure that result of csOutputDir + csPlanoName + csExtension is not getting implicitly cast to pointer and then going out of scope.
using a string conversion macro seems to have solved my problem, successfully tested outcome 10+ times.
CString csFullpath = csOutputDir + csPlanoName + csExtension;
docInfo.lpszOutput = CT2W(csFullpath);

How Matlab knows there is a .mex64 file and avoid infinity "compiling" loop

I created a MyMex.m and a MyMex.cpp. Inside the .m I compile the .cpp using mex. It should happen only if the .mex64 does not exists. The .mex64 is complite to a directory in Matlab PATH. But Matlab will keep running the .m on an infinity loop if I don't set the Matlab current working dir to the .mex64 dir. What I'm missing?
MyMex.m:
function [dataOut] = MyMex(dataIn)
mexCppFile = 'MyMex.cpp';
mexCmd = 'mex MyMex.cpp;';
fprintf('\nFile %s not compiled yet, compiling it now...\n%s\n',mexCppFile,mexCmd);
fileFullPath = which(mexCppFile);
if size(fileFullPath,2) > 0 && exist(fileFullPath,'file')
[fileDir, fileName, ext] = fileparts(fileFullPath);
curDir = pwd;
cd(fileDir);
mex MyMex.cpp;
cd(curDir);
else
error('prog:input','Unable to find %s to compile it. Check if the file is in the current dir or in the Matlab PATH!',mexCppFile);
end
% Call C++ mex
[dataOut] = MyMex(dataIn)
end
Edit to defend myself from the comments that I did a infinity loop:
Matlab was supposed to know that there is a compiled version of the function. I don't know how it does it and my problem is related to that, since some times it finds the function some times it doesn't.
Here is a consolidated online mex sample that does the same "infinity" thing and work smoothly:
2D interpolation
His code in mirt2D_mexinterp.m:
% The function below compiles the mirt2D_mexinterp.cpp file if you haven't done it yet.
% It will be executed only once at the very first run.
function Output_images = mirt2D_mexinterp(Input_images, XI,YI)
pathtofile=which('mirt2D_mexinterp.cpp');
pathstr = fileparts(pathtofile);
mex(pathtofile,'-outdir',pathstr);
Output_images = mirt2D_mexinterp(Input_images, XI,YI);
end
Maybe the .m and the .mex64 need to be on the same folder.
It all comes down to Matlab's search path.
Mex-files are prioritized over m-files if they are on the same level in the path. And files in the current directory take precedence over files found elsewhere in the matlab search path.
So when you experience an infinite loop, it is clear that the m-file is locate higher in the search path than the mex-file.
In essence, all is fine if the two files are in the same folder.

Compile a program with local file embedded as a string variable?

Question should say it all.
Let's say there's a local file "mydefaultvalues.txt", separated from the main project. In the main project I want to have something like this:
char * defaultvalues = " ... "; // here should be the contents of mydefaultvalues.txt
And let the compiler swap " ... " with the actual contents of mydefaultvalues.txt. Can this be done? Is there like a compiler directive or something?
Not exactly, but you could do something like this:
defaults.h:
#define DEFAULT_VALUES "something something something"
code.c:
#include "defaults.h"
char *defaultvalues = DEFAULT_VALUES;
Where defaults.h could be generated, or otherwise created however you were planning to do it. The pre-processor can only do so much. Making your files in a form that it will understand will make things much easier.
The trick I did, on Linux, was to have in the Makefile this line:
defaultvalues.h: defaultvalues.txt
xxd -i defaultvalues.txt > defaultvalues.h
Then you could include:
#include "defaultvalues.h"
There is defined both unsigned char defaultvalues_txt[]; with the contents of the file, and unsigned int defaultvalues_txt_len; with the size of the file.
Note that defaultvalues_txt is not null-terminated, thus, not considered a C string. But since you also have the size, this should not be a problem.
EDIT:
A small variation would allow me to have a null-terminated string:
echo "char defaultvalues[] = { " `xxd -i < defaultvalues.txt` ", 0x00 };" > defaultvalues.h
Obviously will not work very well if the null character is present inside the file defaultvalues.txt, but that won't happen if it is plain text.
One way to achieve compile-time trickery like this is to write a simple script in some interpreted programming language(e.g. Python, Ruby or Perl will do great) which does a simple search and replace. Then just run the script before compiling.
Define your own #pramga XYZ directive which the script looks for and replaces it with the code that declares the variable with file contents in a string.
char * defaultvalues = ...
where ... contains the text string read from the given text file. Be sure to compensate for line length, new lines, string formatting characters and other special characters.
Edit: lvella beat me to it with far superior approach - embrace the tools your environment supplies you. In this case a tool which does string search and replace and feed a file to it.
Late answer I know but I don't think any of the current answers address what the OP is trying to accomplish although zxcdw came really close.
All any 7 year old has to do is load your program into a hex editor and hit CTRL-S. If the text is in your executable code (or vicinity) or application resource they can find it and edit it.
If you want to prevent the general public from changing a resource or static data just encrypt it, stuff it in a resource then decrypt it at runtime. Try DES for something small to start with.

Tracking code versions in an executable

I have a reasonable sized ( around 40k lines) machine learning system written in C++. This is still in active development and I need to run experiments regularly even as I make changes to my code.
The output of my experiments is captured in simple text files. What I would like to do when looking at these results is have some way of figuring out the exact version of the code that produced it. I usually have around 5 to 6 experiments running simultaneously, each on a slightly different version of the code.
I would like to know for instance that a set of results was obtained by compiling version 1 of file A, version 2 of file B etc (I just need some identifier and the output of "git describe" will do fine here ).
My idea is to somehow include this info when compiling the binary. This way, this can be printed out along with the results.
Any suggestions how this can be done in a nice way. In particular, any nice way of doing this with git?
I generate a single source file as part of my build process that looks like this:
static const char version_cstr[] = "93f794f674 (" __DATE__ ")";
const char * version()
{
return version_cstr;
}
Then its easy to log the version out on startup.
I originally used a DEFINE on the command line, but that meant every version change everything got recompiled by the build system - not nice for a big project.
Here's the fragment of scons I use for generating it, maybe you can adapt it to your needs.
# Lets get the version from git
# first get the base version
git_sha = subprocess.Popen(["git","rev-parse","--short=10","HEAD"], stdout=subprocess.PIPE ).communicate()[0].strip()
p1 = subprocess.Popen(["git", "status"], stdout=subprocess.PIPE )
p2 = subprocess.Popen(["grep", "Changed but not updated\\|Changes to be committed"], stdin=p1.stdout,stdout=subprocess.PIPE)
result = p2.communicate()[0].strip()
if result!="":
git_sha += "[MOD]"
print "Building version %s"%git_sha
def version_action(target,source,env):
"""
Generate file with current version info
"""
fd=open(target[0].path,'w')
fd.write( "static const char version_cstr[] = \"%s (\" __DATE__ \")\";\nconst char * version()\n{\n return version_cstr;\n}\n" % git_sha )
fd.close()
return 0
build_version = env.Command( 'src/autogen/version.cpp', [], Action(version_action) )
env.AlwaysBuild(build_version)
You can use $Id:$ in your source file, and Git will substitute that with the sha1 hash, if you add the file containing this phrase in .gitattributes with the option "ident" (see gitattributes).