Calling Matlab function from .net(C#) by using MLApp.Feval() - c#

I tried to use Matlab function from my .net project
function [HR] = getHR(signal)
Fs = 200;
index = pan_tompkin(signal,Fs);
index = index(2:end-1);
idx_dur = (index(end) - index(1))/Fs;
idx_cnt = length(index)-1;
idx_int = idx_dur/idx_cnt;
HR = round(60/idx_int);
end
This is my Matlab code
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(#"cd C:\Users\User\Desktop");
object result = null;
matlab.Feval("getHR", 1, out result,input_Data);
object[] res = result as object[];
tmp_HR = Convert.ToInt32(res[0]);
And this is part of my .net code where calling Matlab function
input_Data is 2000x1 double array
When I run this program, error is occur that "Undefined function 'getHR' for input arguments of type 'double'." on Matlab.Feval line
Someone advised me to 'varargin' to solve this problem, but I can not find the answer(I don't think it is necessary)
How can I revise my code to fix this problem?
I can not use the way to use Matlab compiler SDK or Matlab coder
maybe have to use only MLApp to solve this problem

Related

How can I properly call emgucv retrieve command in Visual C++?

I'm trying to translate a piece of code from visual c# to visual c++ and can't seem to translate this bit:
Mat m = new Mat();
capture.Retrieve(m);
pictureBox1.Image = m.ToImage<Bgr, byte>().Bitmap;
so far i've written
Mat^ m = gcnew Mat();
Emgu::CV::Capture::Retrieve(m);
pictureBox1->Image = m->ToImage<Bgr, Byte>()->Bitmap;
but i get the following errors
(E1767 function "Emgu::CV::Capture::Retrieve" cannot be called with the given argument list)
(E0304 no instance of function template "Emgu::CV::Mat::ToImage" matches the argument list)
Any help would be appreciated.

Using C++ method in c#

I'm writing a c# console application that uses a C++ class library. In C++ language class library I have a method:
public:bool GetMDC(char fileName[], char mdcStrOut[]){
// My Code goes Here
}
This method gets a file path in fileName parameter and puts a value in mdcStrOut.
I add this class library as reference to my C# console application. when I want to call GetMDC method the method needs two sbyte parameters. So it's signature in c# is GetMDC(sbyte* fileName, sbyte* mdcStrOut).
My code looks like this:
unsafe{
byte[] bytes = Encoding.ASCII.GetBytes(fileName);
var _mdc = new TelsaMDC.TelsaMDCDetection();
var outPut = new sbyte();
fixed (byte* p = bytes)
{
var sp = (sbyte*)p;
//SP is now what you want
_mdc.GetMDC(sp, &outPut);
}
}
It works without error. But the problem is that outPut variable only contains the first character of mdcStrOut. I'm unfamiliar with C++. I know that I'm passing the memory address of output to the GetMDC. So how can I get the value of it in my console application?
EDIT
when I declare output variable like this var outPut = new sbyte[MaxLength] I get an error on _mdc.GetMDC(sp, &outPut); line on the & sign. It says: Cannot take the address of, get the size of, or declare a pointer to a managed type ('sbyte[]')
The variable outPut is a single byte.
You need to create a receive buffer, for example, var outPut = new sbyte[MaxLength].
unsafe{
byte[] bytes = Encoding.ASCII.GetBytes(fileName);
var _mdc = new TelsaMDC.TelsaMDCDetection();
var outPut = new sbyte[256]; // Bad practice. Avoid using this!
fixed (byte* p = bytes, p2 = outPut)
{
var sp = (sbyte*)p;
var sp2 = (sbyte*)p2;
//SP is now what you want
_mdc.GetMDC(sp, sp2);
}
}
Also, I recommend to rewrite the code to avoid possible buffer overflow because the function GetMDC does not know the size of the buffer.

c# console application run matlab function

I have some code written in Matlab however I wish to call this code from a C# console application.
I do not require any data to be returned from Matlab to my app (although if easy would be nice to see).
There appears to be a few options however not sure which is best. Speed is not important as this will be an automated task.
MATLAB has a .Net interface that's well-documented. What you need to do is covered in the Call MATLAB Function from C# Client article.
For a simple MATLAB function, say:
function [x,y] = myfunc(a,b,c)
x = a + b;
y = sprintf('Hello %s',c);
..it boils down to creating an MLApp and invoking the Feval method:
class Program
{
static void Main(string[] args)
{
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp();
// Change to the directory where the function is located
matlab.Execute(#"cd c:\temp\example");
// Define the output
object result = null;
// Call the MATLAB function myfunc
matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world");
// Display result
object[] res = result as object[];
Console.WriteLine(res[0]);
Console.WriteLine(res[1]);
Console.ReadLine();
}
}

R.NET invoke function does not work

I have all the necessary requirements when using the R.NET from http://rdotnet.codeplex.com/
My code works just fine on R Studio, however no luck on GUI. Can anybody let me know what I am doing wrong please?
REngine.SetEnvironmentVariables(#"C:\Program Files\R\R-3.1.1\bin\i386", #"C:\Program Files\R\R-3.1.1");
engine = REngine.GetInstance();
engine.Evaluate(#"source('C:/Users/achugh/Documents/Graphs/characterization.r')");
engine.Evaluate(#"source('C:/Users/achugh/Documents/Graphs/sliderDataToComputer.r')");
var sliderfunc = engine.Evaluate("sliderdata_yprofile").AsFunction();
var directory = engine.CreateCharacterVector(new[] { "C:/Users/achugh/Documents/Graphs/data" });
var oldset = sliderfunc.Invoke(new SymbolicExpression[] { directory }).AsDataFrame();
But for some reason the 'oldset' always evaluates to NULL. I already tried testing this via R-Studio
please advice?
Are you absolutely sure your function returns a data frame and not a matrix? The following behaves exactly as expected, and as you describe. I am working from the latest code but this part of R.NET is identical to the latest 1.5.16. Please mark this post as an answer if indeed correct, just not to confuse readers as to the behavior of R data coercion.
var funcDef = #"function(lyrics) {return(data.frame(a=1:4, b=5:8))}";
var f = engine.Evaluate(funcDef).AsFunction();
var x = f.Invoke(engine.CreateCharacter("Wo willst du hin?"));
Assert.True(x.IsDataFrame());
Assert.True(x.IsList());
var df = x.AsDataFrame();
Assert.NotNull(df);
funcDef = #"function() {return(as.matrix(data.frame(a=1:4, b=5:8)))}";
f = engine.Evaluate(funcDef).AsFunction();
x = f.Invoke();
Assert.False(x.IsDataFrame());
Assert.False(x.IsList());
df = x.AsDataFrame();
Assert.Null(df);
var nm = x.AsNumericMatrix();
Assert.NotNull(nm);
Answer:
var oldset = sliderfunc.Invoke(new SymbolicExpression[] { directory }).AsDataFrame();
change the above line to :
var oldset = sliderfunc.Invoke(new SymbolicExpression[] { directory }).AsNumericMatrix();
The reason are unknown, although the script is returning a data frame , but it fails to recognize this as data frame but recognizes this as Numeric Matrix.

Calling MATLAB Software from a C# Client - Obtain scalar result

I am currently using this preliminary code:
static void Main(string[] args)
{
try
{
Type matlabtype;
matlabtype = Type.GetTypeFromProgID("matlab.application");
object matlab;
matlab = Activator.CreateInstance(matlabtype);
Execute(matlabtype, matlab, "clear;");
Execute(matlabtype, matlab, "path(path,'H:/bla/bla');");
Execute(matlabtype, matlab, "Object = ClassName();");
Execute(matlabtype, matlab, "Object.parameter1 = 100;");
Execute(matlabtype, matlab, "Object.parameter2 = 300;");
object o = Execute(matlabtype, matlab, "Object.ComputeSomething()");
}
catch (Exception e)
{
}
}
to create an object of a particular class, set some properties and compute something. Here:
ComputeSomething();
returns a scalar.
I am just wondering whether this is the best way to program this and what’s the cleanest way to obtain the actual scalar value without using string operations (e.g. remove ans =)?
Thanks.
Christian
You can retrieve data from matlab using a few commands. To get a scalar you can call GetVariable.
Execute(matlabtype, matlab, "result = Object.ComputeSomething()");
GetVariable(matlabtype, matlab, "result", "base")
see Call MATLAB COM Automation Server for available calls.

Categories

Resources