c# console application run matlab function - c#

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();
}
}

Related

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

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

C# - Dynamically create function body from user input string

I am trying to create a C# program that lets user's provide an implementation for for a function by inputting text into a text box. I provide the function header (input types, output type), they just need to provide actual implementation. I then store that function to call later. They might need to import something from the .NET framework, but nothing outside of it.
I don't care about security, this is just for a tool for internal use.
Is there an easy way to do this in .NET?
The usage would look something like (need to implement the CompileUserFunction function, which takes in an int and returns an object):
Func<int, object> CreateUserFunction(string input) {
Func<int, object> userFunc = CompileUserFunction(input);
return (i) => userFunc(i);
}
public void DoSomething() {
List<Func<int, object>> userFuncs = new List<Func<int, object>>();
string userInput = #"DateTime t = DateTime.Now;
t.AddDays(i);
return t;";
userFuncs.Add(CreateUserFunction(userInput));
userFuncs.Add(CreateUserFunction("return i;"));
userFuncs.Add(CreateUserFunction("i = i * 5; return i;"));
var result = userFuncs[0](5);
}
You can use code generation libs for that task.
I advice you to use Roslyn scripting API. I have done a similar task - parsing a string into delegate with it. The following example is taken from this link: https://blogs.msdn.microsoft.com/csharpfaq/2011/12/02/introduction-to-the-roslyn-scripting-api/
You will find there more examples
using Roslyn.Scripting.CSharp;
namespace RoslynScriptingDemo
{
class Program
{
static void Main(string[] args)
{
var engine = new ScriptEngine();
engine.Execute(#"System.Console.WriteLine(""Hello Roslyn"");");
}
}
}
There are other code generation tools and libs:
CodeDom - an old .Net code generation Framework. Probably can be used here but is more tricky.
https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/using-the-codedom
There were some libraries which were used to convert strings to Linq Expression trees, but it all seems to be outdated now.
There is also a possibility to create a Dynamic Method via Reflection.Emit but it is very low level - you need to define method implementation in IL instructions.

Pass variable from C# - IronPython to a Python script

I have a WPF application. For the purpose of this question, let's say it's a simple Window with a button. When I click on that button, I would like a Python script to be executed. Therefore, I went looking around and found out that I can run Python scripts using IronPython. Part1 works well, it runs the python scripts. From what I've gathered from looking around the web, Part2 is what I should do if I want to call a specific method.
private void btnWhatever_Click(object sender, RoutedEventArgs e)
{
//Basic engine to run python script. - Part1
ScriptEngine engine = Python.CreateEngine();
string pythonScriptPath = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
ScriptSource source = engine.CreateScriptSourceFromFile(pythonScriptPath + "/python.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
//Part2
Object myclass = engine.Operations.Invoke(scope.GetVariable("pythonScriptClass"));
object[] parameters = new object[] { "Hi",3 };
engine.Operations.InvokeMember(myclass, "theMethod", parameters);
}
The problem is, I kept getting 'Microsoft.Scripting.ArgumentTypeException' happened in Microsoft.Dynamic.dll : theMethod() takes exactly 2 arguments (3 given).
I understand from that error that I'm giving 3 arguments instead of 2 but I can't call a specific method another way from what I found out. I'm pretty new to IronPython and Python in general but here is a script example :
class pythonScriptClass:
def swapText(text, number):
return text[number:] + text[:number]
def getLetterIndex(letter, text):
for k in range(len(text)):
if (letter== text[k]):
return k
return -1
def theMethod(text , number):
result= swapText("textToBeSwaped", number)
toBeReturned = ""
for letter in text:
if letter in "abcdefghijklmnopqrstuvwxyz":
toBeReturned = toBeReturned + result[getLetterIndex(letter, result)]
return toBeReturned
My ultimate goal for the moment is to get this to work and therefore be able to call theMethod() from the Python script and get the returned value using C# - IronPython.
I have tried other methods such as : scope.SetVariable("key","value"); but I got the same error.
As for python member method, the first argument is self.
class pythonScriptClass:
def theMethod(self, text, number):
# and call self.swapText(...)
This is why the number of arguments went wrong.

How to call Lua Functions with AluminumLua in C#?

I'm just learning about Lua and trying to integrate it with C# and mono (on Linux). After some looking around, I found AluminumLua as a wrapper to do so.
I've successfully being able to call from lua to C#, but I can't see the way to call from C# to lua:
lua (test.lua):
HelloWorld()
function print_test()
print("hi")
return 1
end
C#
var context = new LuaContext ();
context.AddBasicLibrary ();
context.AddIoLibrary ();
context.SetGlobal ("HelloWorld", LuaObject.FromDelegate(new Action(HelloWorld)));
var parser = new LuaParser (context, "test.lua");
parser.Parse ();
...
public static void HelloWorld() {
Console.Write("HelloWorld");
}
That's cool, but... How can I call the function "print_test", get its output result from C#?
From looking at the source, LuaContext has a Get method which returns a LuaObject. After you have a reference to that LuaObject you can try to turn it into a LuaFunction using AsFunction and IsFunction.
Something along the lines of this should work:
// ...
var print_test = context.Get("print_test");
if (print_test.IsFunction)
{
print_test.AsFunction()(null);
}
else
{
Console.Write("print_test not a lua function!");
}
// ...

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