I am trying to to write a very simple mex file, let's say just to try out the way it works. I have gone through a lot of materials and more I read, more I get confused. I need this to further write a mex file that interacts with external hardware. Please help!
// header file - printing.h //
#include<iostream>
class printing
{
public:
void name();
void age();
};
// cpp file - printing.cpp //
#include<iostream>
#include "mex.h"
#include "matrix.h"
#include "printing.h"
#include <string>
using namespace std;
void mexFunction(int nlhs, mxArray*plhs[],
int nrhs, const mxArray *prhs[])
{
printing p1;
p1.name();
p1.age();
}
void printing::name()
{
cout << "NAME" << endl;
}
void printing::age()
{
cout << "20" << endl;
}
// .m file - test.m //
sprintf ('WELCOME')
printing()
When i run the test.m file, I would like to see
WELCOME
NAME
20
However I see only welcome. I understand that I have not updated the plhs[] array. But all I want to do is execute something inside mexFunction.Why wouldn't the cout inside name() and age() achieve this?
Also, how do i confirm that name() and age() are executed?
The call to cout will not print to the MATLAB console, you need to use the MEX printf function.
mexPrintf("NAME\n");
Related
So I have 3 files in a single folder, my main file (Q1.cpp), my header file (pa2Functions.h), and my implementation file, (pa2Functions.cpp). When I call my function, I don't get any output and I am extremely confused as to why. I have included the contents of all 3 files below.
pa2Functions.h
#include <iostream>
using namespace std;
void initialize();
pa2Functions.cpp
#include <iostream>
#include "pa2Functions.h"
using namespace std;
void initialize(){
cout << "hello" << endl;}
Q1.cpp
#include <iostream>
#include "pa2Functions.h"
using namespace std;
int main(){
void initialize();
}
I compile with
g++ Q1.cpp pa2Functions.cpp -o Output
But when I run the output I just don't get anything. Any help would be greatly appreciated.
In main, remove the void in front of initialize. You're declaring the function again, not calling it.
int main(){
initialize();
}
I have a project that has the main method accessing another method from another source file, BigDog(int). I'm pretty sure the code is right but CodeBlocks seems to not be able to detect the definition of the method unless I build the other file using debug build in CodeBlocks. In Release, I get the following error when building:
Error: undefined reference to 'BigDog(int)'
Why is that so?
main.cpp
#include <iostream>
using namespace std;
void BigDog(int KibblesCount);
int main()
{
BigDog(3);
return 0;
}
mystuff.cpp
#include <iostream>
using namespace std;
void BigDog(int KibblesCount)
{
cout << KibblesCount;
}
If you're adding a new file in codeblocks, make sure to check the checkmarks in the dialog to add it to both the debug and the release build.
Also its better practice to move your declarations to a header file and include that where needed, like this:
main.cpp:
#include "mystuff.h"
int main()
{
BigDog(3);
return 0;
}
mystuff.h:
#pragma once
void BigDog(int KibblesCount);
mystuff.cpp:
#include "mystuff.h"
#include <iostream>
void BigDog(int KibblesCount)
{
// add a newline so the line gets printed immediately
std::cout << KibblesCount << "\n";
}
I am trying to implement an Eigen library pseudo-inverse function in a Matlab MEX-file. It compiles successfully but crashes when I run it.
I am trying to follow the FAQ on how to implement a pseudo-inverse function using the Eigen library.
The FAQ suggests adding it as a method to the JacobiSVD class but since you can't do that in C++ I'm adding it to a child class. It compiles successfully but then crashes without an error message. It successfully outputs "hi" without crashing if I comment out the line with the .pinv call so that's where the problem is arising. To run, I just compile it (as test.cpp) and then type test at the command line. I am using Matlab R2019a under MacOS 10.14.5 and Eigen 3.3.7. In my full code I also get lots of weird error messages regarding the pinv code but before I can troubleshoot I need this simple test case to work. This is all at the far limits of my understanding of C++. Any help appreciated.
#include "mex.h"
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <cstdlib>
#include <cmath>
#include <iostream>
using namespace Eigen;
using namespace std;
//https://stackoverflow.com/questions/18804402/add-a-method-to-existing-c-class-in-other-file
class JacobiSVDext : public JacobiSVD<MatrixXf> {
typedef SVDBase<JacobiSVD<MatrixXf>> Base;
public:
using JacobiSVD::JacobiSVD; //inherit constructors //https://stackoverflow.com/questions/347358/inheriting-constructors
MatrixXf pinv() //http://eigen.tuxfamily.org/index.php?title=FAQ
{
eigen_assert(m_isInitialized && "SVD is not initialized.");
double pinvtoler=1.e-6; // choose your tolerance wisely!
JacobiSVDext::SingularValuesType singularValues_inv=m_singularValues;
for ( long i=0; i<m_workMatrix.cols(); ++i) {
if ( m_singularValues(i) > pinvtoler )
singularValues_inv(i)=1.0/m_singularValues(i);
else singularValues_inv(i)=0;
}
return m_matrixV*singularValues_inv.asDiagonal()*m_matrixU.transpose();
};
};
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
MatrixXf X = MatrixXf::Random(5, 5);
JacobiSVDext svd(X);
MatrixXf Y=svd.pinv();
cout << Y << endl;
cout << "hi" << endl;
}
The expected result is to output the pseudo-inverse of the random matrix and also "hi". Instead it crashes without an error message.
When constructing the Eigen::JacobiSVD object, you fail to request that matrices U and V should be computed. By default, these are not computed. Obviously, accessing these matrices if they are not computed will cause a segmentation violation.
See the documentation to the constructor. A second input argument must specify either ComputeFullU | ComputeFullV, or ComputeThinU | ComputeThinV. The thin ones are preferable when computing the pseudo-inverse, as the rest of the matrices are not needed.
I would not derive from the JacobiSVD class just to add a method. Instead, I would simply write a free function. This is both easier, and allows you to use only the documented portions of the Eigen API.
I wrote the following MEX-file, which works as intended (using code I already had for this computation). It does the same, but in a slightly different way that avoids writing an explicit loop. Not sure this way of writing it is very clear, but it works.
// Compile with:
// mex -v test.cpp -I/usr/local/include/eigen3
#include "mex.h"
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <cstdlib>
#include <cmath>
#include <iostream>
Eigen::MatrixXf PseudoInverse(Eigen::MatrixXf matrix) {
Eigen::JacobiSVD< Eigen::MatrixXf > svd( matrix, Eigen::ComputeThinU | Eigen::ComputeThinV );
float tolerance = 1.0e-6f * float(std::max(matrix.rows(), matrix.cols())) * svd.singularValues().array().abs()(0);
return svd.matrixV()
* (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0).matrix().asDiagonal()
* svd.matrixU().adjoint();
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
Eigen::MatrixXf X = Eigen::MatrixXf::Random(5, 5);
Eigen::MatrixXf Y = PseudoInverse(X);
std::cout << Y << '\n';
std::cout << "hi\n";
}
I have a string function written in rtstring.c file which simply accept a string and return back the same string.
Then i have included this file in a body.cpp file and i want to pass string from
this file to c file.
How can I do this please help
My code
rtstring.c
#include <stdio.h>
char * rtstr(char * s)
{
return s;
}
body.cpp
#pragma once
#include "header.h"
#include "rtstring.c"
mystring::mystring(string str)
{
st=str;
}
string mystring::strreturn(string s1)
{
st=rtstr(s1);
return st;
}
header.h
#pragma once
class mystring
{
public:
mystring(string a);
string strreturn(string s1);
private:
string st;
}
main.cpp
#include <iostream>
using namespace std;
#include "header.h"
int main()
{
string rs,s="hi hello";
mystring str1(s);
rs=str.strreturn(s);
cout<<"string from c"<<rs;
return 0;
}
I an getting an error of return type mismatch and many associated error. Please help if there is anyway to deal with it. an example will be helpfull.
Thanks in advance
I an getting an error of return type mismatch
If you were to read the complete error message, I'm sure it would tell you that this is the problem:
char * rtstr(char * s)
// ^^^^^^
string mystring::strreturn(string s1)
// ^^^^^^
{
st=rtstr(s1);
// ^^
You are trying to pass a std::string into a function that instead expects char*.
To solve the problem, don't try to pass a std::string to functions that expect a char*. You'll probably find std::string::c_str() member function useful.
#include "rtstring.c"
Don't include source files. Especially don't include source files that were written in another language.
To call a function defined in another source file, just declare the function in the calling source and link the object file of the other source. Remember to set the language linkage when declaring cross-language functions. You'll find header files useful for including function declarations.
Your code is not much clear to me, but I understand your question.
So, accordingly, one of the simplest way is to write the string into a file using C programming and then reading the same file in your cpp program.
Your C program to write into a file:
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char s[1000];
FILE *fptr;
fptr = fopen("program.txt", "w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter your string:\n");
gets(s);
fprintf(fptr,"%s", s);
fclose(fptr);
return 0;
}
Your cpp program something like this to read the same file.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
char c,fname[20] = 'program.txt';
clrscr();
ifstream in(fname);
if(!in)
{
cout<<"File Does not Exist";
getch();
return;
}
cout<<"\n\n";
while(in.eof()==0)
{
in.get(c);
cout<<c;
}
getch();
}
Another option could be to use pipe() function. More details.
I have figured it out a way which suits my requirement best.
I appreciate all your help thanks.
Changes i have done is as follows
body.cpp
`
string mystring::strreturn(string s1)
{
char *p,arr[9];
char *c=new char[s1.size()+1];
copy(s1.begin(),s1.end(),c);
c[s1.size()]='\0';
p=rtstr(c);
strcpy(arr,p);
st=arr;
return st;
}
`
please insert appropriate headers.
"using namespace std;" both in header.h and body.cpp
"#include" in header.h
First of all, you don't include source files. You should make rtstring.c it's own header, in which you declare the function rtstr.
Second, you're using a C++ compiler. If you want it to emulate C, you use using "C" { ... }. There are still fundamental differences between proper C and C++, so you're still using a C subset of C++, not actual C.
And finally, if you want to convert an std::string to a C string (char*), you can use its c_str() function.
On my mainfile, I wish to pass my loaded struct array from first function to second function ,both functions are in the source file(in.cpp). I was not able to do so even if I defined struct on main file, because firstly array cannot be return only pass by reference; I tried pass by reference also but does not work
#include "internetUsage.h"
#include "abc.h"
#include<fstream>
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
char filename[20];
ifstream infile;
cout<<"enter file name: \n";
cin.getline(filename,20);
infile.open(filename);
newRecord(infile,filename);
updateRecord(infile,filename);
return 0;
}
This is my source file (in.cpp); after I loaded my struct array in my first function, I could not figure out how to display on my second function(updateRecord())
#include "internetUsage.h"
#include "abc.h"
#include <fstream>
#include<iostream>
using namespace std;
void newRecord(ifstream &infile,char filename[])
{
Info customer[50];
for(int i; i<6; i++)
{
infile>>customer[i].num;
infile>>customer[i].name;
infile>>customer[i].name2;
infile>>customer[i].charge;
}
}
void updateRecord(ifstream &infile,char filename[])
{
for(int j; j<6; j++)
{
cout<<customer[j].num<<endl;
cout<<customer[j].name<<endl;
cout<<customer[j].name2<<endl;
cout<<customer[j].charge<<endl;
}
}
This is my header file for two functions(internetUsage.h)
#include <fstream>
#include<cstring>
#include<iostream>
using namespace std;
void newRecord(ifstream &infile, char filename[]);
void updateRecord(ifstream &infile,char filename[]);
This is my header file for struct(abc.h)
#include<iostream>
using namespace std;
struct Info
{
int num;
char name[200];
char name2[200];
double charge;
};
you should define it Info customer[50]; as global variable , not local variable
define Info customer[50]; in main(),
Change newRecord() interface to add two parameters: Info * customer, int sizeCustomer
Change newRecord() internal loop to control customer's overflow, something like "if(j >= sizeCustomer) break;"
Change newRecord() interface to return number of customers have been read
Change updateRecord() interface to add two parameters: const Info * customer, int actualCustomerSize
Change updateRecord() internal loop to run for actualCustomerSize only, for example by modifing for(;j!=actualCustomerSize;)
Make changes in main()
Enjoy
Declare that structure as global in the file where you are loading that structure and then use the extern keyword along with the structure name in all the files where you want to use that function.
DO check this link:
http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/