Using Dymola 2017.
Case A) Calling an external c-script
I have had success implementing simple external c functions that have no “# include <-->” statements:
Modelica Function:
function chirp
input Modelica.SIunits.AngularVelocity w_start;
input Modelica.SIunits.AngularVelocity w_end;
input Real A;
input Real M;
input Real t;
output Real u "output signal";
external "C" u=chirp(w_start,w_end,A,M,t)
annotation(IncludeDirectory="modelica://ExternalFuncTest/Resources/Source/", Include="#include \"chirp.c\"");
end chirp;
C-script:
double chirp(double w1, double w2, double A, double M, double time)
{
double res;
res=A*cos(w1*time+(w2-w1)*time*time/(2*M));
return res;
}
Case B) Calling an external function in a .dll file
I also have had success in calling external functions within a compiled dll:
Modelica Function:
function bessel_Jn
"Bessel function of the 1st kind (regular cylindrical) of order n"
extends Modelica.Icons.Function;
input Integer n;
input Real x;
output Real y;
external "C" y=gsl_sf_bessel_Jn(n,x) annotation(LibraryDirectory="modelica://ExternalFuncTest/Resources/Source/gsl-1.8/", Library="libgsl");
end bessel_Jn;
Case C) Calling an external c-script which uses functions from an external .dll via headers
What I want to do now is create a c function that does more interesting things. My current approach is to include header files in the c function that references the compiled dll (in this case a compiled version of the GNU scientific library). This example has the header (although it does not do anything for the moment).
Modelica Function:
function chirp
input Modelica.SIunits.AngularVelocity w_start;
input Modelica.SIunits.AngularVelocity w_end;
input Real A;
input Real M;
input Real t;
output Real u "output signal";
external "C" u=chirp(w_start,w_end,A,M,t)
annotation(LibraryDirectory="modelica://ExternalFuncTest/Resources/Source/gsl-1.8/", Library="libgsl",
IncludeDirectory="modelica://ExternalFuncTest/Resources/Source/", Include="#include \"chirp.c\"");
end chirp;
C-cript:
#include <gsl/gsl_sf_bessel.h> //<-- note the additional header
double chirp(double w1, double w2, double A, double M, double time)
{
double res;
res=A*cos(w1*time+(w2-w1)*time*time/(2*M));
return res;
}
When attempting to call the function above the error indicates failure to translate and nothing else due to the existence of the header file. If the header file is commented out the function will run as expected.
Please let me know if you have any insight as to how to properly go about implementing this feature. Thank you.
For reference: The image below is the path to the external c-script and .dll.
Wrong Path: Note gsl header folder is within gsl-1.8 folder
Correct Path: Note gsl header folder is at the same level as gsl-1.8 folder
UPDATE: Header works but function call causes translation to fail
I have updated the c-script to now call a function that should be handeled by the header. In its current state it won't work. Perhaps it can't find the .dll file although its specified in the modelica code? Do I have to include a load .dll command in the c-scripts?
#include <gsl/gsl_sf_bessel.h>
double chirp(double w1, double w2, double A, double M, double time)
{
double res;
double y;
res=A*cos(w1*time+(w2-w1)*time*time/(2*M));
y = gsl_sf_bessel_j0(time); // <-- Calls a function from the .dll file using the header
return res;
}
I believe this can only be resolved with relative include paths or future tools that implement future Modelica Language Specification 3.4. See https://trac.modelica.org/Modelica/ticket/2103 for the corresponding update on the Modelica Language Specification.
You set include directory to modelica://ExternalFuncTest/Resources/Source/gsl-1.8/
and then use #include <gsl-1.8/gsl/gsl_errno.h>
Do you really have a directory gsl-1.8 in the directory gsl-1.8 (some projects have such a structure - but it is generally rare)? If that is not the case change to #include <gsl/gsl_errno.h>.
I believe hierarchical includes are also searched in the path and thus that should work; otherwise you could always set includeDirectory to modelica://ExternalFuncTest/Resources/Source/gsl-1.8/gsl and use #include <gsl_errno.h>.
Referencing compiled library headers from c-scripts that are called by a Modelica external function call is possible.
However, it is still not determined if there is an efficient method to access the .dll. This is discussed in a follow up question External Functions: Alternative Method to use .dll from a C-script.
The solution that allowed the header files to be recognized is presented. Thanks to all who responded in helping figure this out.
Step 1) Create Folder Structure
Modelica looks in default directories automatically for external function dependencies. Section 12.9.4 of modelica.org/documents/ModelicaSpec33Revision1.pdf
The default location that Modelica looks for compiled libraries is a folder called Library within the Resources folder of your project:
LibraryDirectory="modelica://LibraryPackageName/Resources/Library"
For header files and c-scripts the default location is a folder called Include within the Resources folder of your project:
IncludeDirectory="modelica://LibraryPackageName/Resources/Include"
To specify alternative directories follow the modelica spec document. As of Modelica Specification 3.3 Rev 1 you can only specify one LibraryDirectory and one IncludeDirectory. Though this may be addressed in the future https://trac.modelica.org/Modelica/ticket/2103.
Summary of Overall Folder Structure
Step 2) Create Modelica Function and C-Scripts in locations specified in above image
Below are examples that can be used for reference.
Modelica Function
function chirp
input Modelica.SIunits.AngularVelocity w_start;
input Modelica.SIunits.AngularVelocity w_end;
input Real A;
input Real M;
input Real t;
output Real u "output signal";
external "C" u=chirp(w_start,w_end,A,M,t)
annotation(Library="libgsl",Include="#include \"chirp.c\"");
end chirp;
C-Script
#include <gsl/gsl_sf_bessel.h>
double chirp(double w1, double w2, double A, double M, double time)
{
double res;
res=A*cos(w1*time+(w2-w1)*time*time/(2*M));
return res;
}
Related
I meet a problem in the s function builder, I have to use a temp structure variable to transport the inputs to the extended C function.
Background: csolve function is a quadratic programming solver generated by CVXGEN for my QP problem, and I have tested the function in level-2 matlab s-fun. Now I want to use s function builder to genetate the TLC file that support the embedded code generate.
My Problem:
1) I have to use a temp structure variable 'params' to the inputs to csolve function in the outputs panel, could you please help me to solve this problem?
2) I find that in cvxgen folder contains a header file contains 'tic' and 'toc' function, how to use these functions in s function builder?
params.Aeq=Aeq;
params.beq=beq;
params.Aineq=Aineq;
params.bineq=bineq;
params.Smat=Smat;
params.Wmat=Wmat;
params.alpha=alpha;
[vars, status] = csolve(params)
y0=vars.x;
converge=status.converge;
for the attached files please see here
First some background information that you should know:
Matlab and C work completely differently and use different kinds of data types. To call C code from Matlab, so called "mex-functions" are generated. Matlab uses a special data type named mxArray to exchange data between Matlab and these "mex-functions", which are written in C.
In the C program an element (for example a variable) of the type mxArray represents a Matlab value of any data type. Matlab provides some functions (like mxGetData()) to access the actual data of the Matlab data element from the C function: There is some function for checking if the mxArray represents a floating-point value or a string. Another function allows you to convert the value from mxArray to double if the element has a floating-point value.
[vars, status] = csolve(params)
This means you want to call a "mex-function" from an "S-function".
Theoretically, this is possible but it is not as easy as you think:
First of all, the entry point of both types of functions is named mexFunction() in the C code. This means you cannot simply combine the C codes of both functions because in this case you would have two functions with the same name (mexFunction) in your S-function.
You might call the function mexCallMATLAB; however Mathworks writes that this function should not be called from S-functions.
The other possibility would be loading the mex-function using DLL functions (in Windows: LoadLibrary, GetProcAddress, FreeLibrary) and call the function mexFunction() of the mex-function using a function pointer.
However, in this case you have to convert all C data types to mxArray data and the data returned from the mex-function must be converted back ...
... a TLC file that is needed in ... embedded coder
The functions that access data of the mxArray type are only available when Matlab is running.
If you generate code that shall be executable outside Matlab, you cannot use mxArray and therefore you cannot call mex-functions.
The file csolve.c defines four structure variables:
Vars vars;
Params params;
Workspace work;
Settings settings;
And what the file actually does is the following:
Read the structure params (mxArray data type), convert these content to C data types and write the data into the four structure variables above
Call the following code:
steps = solve();
for (i = 0; i < extra_solves; i++)
solve();
The function solve() is defined in the other .c files in the project.
Take the values from the four structure variables and the value step returned by solve() and convert the data to mxArray.
Return the result as [vars, status]
You can define the four variables in your S-function code, fill these structures the same way the file csolve.c does it, call the solve() function as it is shown above and read the data of vars and status directly from the four variables.
You remove csolve.c from your project and add the other .c files of your mex-function to the S-function.
When I was studying for my undergraduate degree in EE, MATLAB required each function to be defined in its own file, even if it was a one-liner.
I'm studying for a graduate degree now, and I have to write a project in MATLAB. Is this still a requirement for newer versions of MATLAB?
If it is possible to put more than one function in a file, are there any restrictions to this? For instance, can all the functions in the file be accessed from outside the file, or only the function that has the same name as the file?
Note: I am using MATLAB release R2007b.
The first function in an m-file (i.e. the main function), is invoked when that m-file is called. It is not required that the main function have the same name as the m-file, but for clarity it should. When the function and file name differ, the file name must be used to call the main function.
All subsequent functions in the m-file, called local functions (or "subfunctions" in the older terminology), can only be called by the main function and other local functions in that m-file. Functions in other m-files can not call them. Starting in R2016b, you can add local functions to scripts as well, although the scoping behavior is still the same (i.e. they can only be called from within the script).
In addition, you can also declare functions within other functions. These are called nested functions, and these can only be called from within the function they are nested. They can also have access to variables in functions in which they are nested, which makes them quite useful albeit slightly tricky to work with.
More food for thought...
There are some ways around the normal function scoping behavior outlined above, such as passing function handles as output arguments as mentioned in the answers from SCFrench and Jonas (which, starting in R2013b, is facilitated by the localfunctions function). However, I wouldn't suggest making it a habit of resorting to such tricks, as there are likely much better options for organizing your functions and files.
For example, let's say you have a main function A in an m-file A.m, along with local functions D, E, and F. Now let's say you have two other related functions B and C in m-files B.m and C.m, respectively, that you also want to be able to call D, E, and F. Here are some options you have:
Put D, E, and F each in their own separate m-files, allowing any other function to call them. The downside is that the scope of these functions is large and isn't restricted to just A, B, and C, but the upside is that this is quite simple.
Create a defineMyFunctions m-file (like in Jonas' example) with D, E, and F as local functions and a main function that simply returns function handles to them. This allows you to keep D, E, and F in the same file, but it doesn't do anything regarding the scope of these functions since any function that can call defineMyFunctions can invoke them. You also then have to worry about passing the function handles around as arguments to make sure you have them where you need them.
Copy D, E and F into B.m and C.m as local functions. This limits the scope of their usage to just A, B, and C, but makes updating and maintenance of your code a nightmare because you have three copies of the same code in different places.
Use private functions! If you have A, B, and C in the same directory, you can create a subdirectory called private and place D, E, and F in there, each as a separate m-file. This limits their scope so they can only be called by functions in the directory immediately above (i.e. A, B, and C) and keeps them together in the same place (but still different m-files):
myDirectory/
A.m
B.m
C.m
private/
D.m
E.m
F.m
All this goes somewhat outside the scope of your question, and is probably more detail than you need, but I thought it might be good to touch upon the more general concern of organizing all of your m-files. ;)
Generally, the answer to your question is no, you cannot define more than one externally visible function per file. You can return function handles to local functions, though, and a convenient way to do so is to make them fields of a struct. Here is an example:
function funs = makefuns
funs.fun1=#fun1;
funs.fun2=#fun2;
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
And here is how it could be used:
>> myfuns = makefuns;
>> myfuns.fun1(5)
ans =
5
>> myfuns.fun2()
ans =
1
The only way to have multiple, separately accessible functions in a single file is to define STATIC METHODS using object-oriented programming. You'd access the function as myClass.static1(), myClass.static2() etc.
OOP functionality is only officially supported since R2008a, so unless you want to use the old, undocumented OOP syntax, the answer for you is no, as explained by #gnovice.
EDIT
One more way to define multiple functions inside a file that are accessible from the outside is to create a function that returns multiple function handles. In other words, you'd call your defining function as [fun1,fun2,fun3]=defineMyFunctions, after which you could use out1=fun1(inputs) etc.
I really like SCFrench's answer - I would like to point out that it can easily be modified to import the functions directly to the workspace using the assignin function. (Doing it like this reminds me a lot of Python's "import x from y" way of doing things)
function message = makefuns
assignin('base','fun1',#fun1);
assignin('base','fun2',#fun2);
message='Done importing functions to workspace';
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
And then used thusly:
>> makefuns
ans =
Done importing functions to workspace
>> fun1(123)
ans =
123
>> fun2()
ans =
1
Along the same lines as SCFrench's answer, but with a more C# style spin..
I would (and often do) make a class containing multiple static methods. For example:
classdef Statistics
methods(Static)
function val = MyMean(data)
val = mean(data);
end
function val = MyStd(data)
val = std(data);
end
end
end
As the methods are static you don't need to instansiate the class. You call the functions as follows:
data = 1:10;
mean = Statistics.MyMean(data);
std = Statistics.MyStd(data);
I define multiple functions in one .m file with Octave and then use the command from within the .m file where I need to make use of the functions from that file:
source("mycode.m");
Not sure if this is available with Matlab.
octave:8> help source
'source' is a built-in function
-- Built-in Function: source (FILE)
Parse and execute the contents of FILE. This is equivalent to
executing commands from a script file, but without requiring the
file to be named `FILE.m'.
You could also group functions in one main file together with the main function looking like this:
function [varargout] = main( subfun, varargin )
[varargout{1:nargout}] = feval( subfun, varargin{:} );
% paste your subfunctions below ....
function str=subfun1
str='hello'
Then calling subfun1 would look like this:
str=main('subfun1')
As of R2017b, this is not officially possible. The relevant documentation states that:
Program files can contain multiple functions. If the file contains only function definitions, the first function is the main function, and is the function that MATLAB associates with the file name. Functions that follow the main function or script code are called local functions. Local functions are only available within the file.
However, workarounds suggested in other answers can achieve something similar.
I have try with the SCFRench and with the Ru Hasha on octave.
And finally it works: but I have done some modification
function message = makefuns
assignin('base','fun1', #fun1); % Ru Hasha
assignin('base', 'fun2', #fun2); % Ru Hasha
message.fun1=#fun1; % SCFrench
message.fun2=#fun2; % SCFrench
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
Can be called in other 'm' file:
printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());
update:
I added an answer because neither the +72 nor the +20 worked in octave for me.
The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).
When I was studying for my undergraduate degree in EE, MATLAB required each function to be defined in its own file, even if it was a one-liner.
I'm studying for a graduate degree now, and I have to write a project in MATLAB. Is this still a requirement for newer versions of MATLAB?
If it is possible to put more than one function in a file, are there any restrictions to this? For instance, can all the functions in the file be accessed from outside the file, or only the function that has the same name as the file?
Note: I am using MATLAB release R2007b.
The first function in an m-file (i.e. the main function), is invoked when that m-file is called. It is not required that the main function have the same name as the m-file, but for clarity it should. When the function and file name differ, the file name must be used to call the main function.
All subsequent functions in the m-file, called local functions (or "subfunctions" in the older terminology), can only be called by the main function and other local functions in that m-file. Functions in other m-files can not call them. Starting in R2016b, you can add local functions to scripts as well, although the scoping behavior is still the same (i.e. they can only be called from within the script).
In addition, you can also declare functions within other functions. These are called nested functions, and these can only be called from within the function they are nested. They can also have access to variables in functions in which they are nested, which makes them quite useful albeit slightly tricky to work with.
More food for thought...
There are some ways around the normal function scoping behavior outlined above, such as passing function handles as output arguments as mentioned in the answers from SCFrench and Jonas (which, starting in R2013b, is facilitated by the localfunctions function). However, I wouldn't suggest making it a habit of resorting to such tricks, as there are likely much better options for organizing your functions and files.
For example, let's say you have a main function A in an m-file A.m, along with local functions D, E, and F. Now let's say you have two other related functions B and C in m-files B.m and C.m, respectively, that you also want to be able to call D, E, and F. Here are some options you have:
Put D, E, and F each in their own separate m-files, allowing any other function to call them. The downside is that the scope of these functions is large and isn't restricted to just A, B, and C, but the upside is that this is quite simple.
Create a defineMyFunctions m-file (like in Jonas' example) with D, E, and F as local functions and a main function that simply returns function handles to them. This allows you to keep D, E, and F in the same file, but it doesn't do anything regarding the scope of these functions since any function that can call defineMyFunctions can invoke them. You also then have to worry about passing the function handles around as arguments to make sure you have them where you need them.
Copy D, E and F into B.m and C.m as local functions. This limits the scope of their usage to just A, B, and C, but makes updating and maintenance of your code a nightmare because you have three copies of the same code in different places.
Use private functions! If you have A, B, and C in the same directory, you can create a subdirectory called private and place D, E, and F in there, each as a separate m-file. This limits their scope so they can only be called by functions in the directory immediately above (i.e. A, B, and C) and keeps them together in the same place (but still different m-files):
myDirectory/
A.m
B.m
C.m
private/
D.m
E.m
F.m
All this goes somewhat outside the scope of your question, and is probably more detail than you need, but I thought it might be good to touch upon the more general concern of organizing all of your m-files. ;)
Generally, the answer to your question is no, you cannot define more than one externally visible function per file. You can return function handles to local functions, though, and a convenient way to do so is to make them fields of a struct. Here is an example:
function funs = makefuns
funs.fun1=#fun1;
funs.fun2=#fun2;
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
And here is how it could be used:
>> myfuns = makefuns;
>> myfuns.fun1(5)
ans =
5
>> myfuns.fun2()
ans =
1
The only way to have multiple, separately accessible functions in a single file is to define STATIC METHODS using object-oriented programming. You'd access the function as myClass.static1(), myClass.static2() etc.
OOP functionality is only officially supported since R2008a, so unless you want to use the old, undocumented OOP syntax, the answer for you is no, as explained by #gnovice.
EDIT
One more way to define multiple functions inside a file that are accessible from the outside is to create a function that returns multiple function handles. In other words, you'd call your defining function as [fun1,fun2,fun3]=defineMyFunctions, after which you could use out1=fun1(inputs) etc.
I really like SCFrench's answer - I would like to point out that it can easily be modified to import the functions directly to the workspace using the assignin function. (Doing it like this reminds me a lot of Python's "import x from y" way of doing things)
function message = makefuns
assignin('base','fun1',#fun1);
assignin('base','fun2',#fun2);
message='Done importing functions to workspace';
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
And then used thusly:
>> makefuns
ans =
Done importing functions to workspace
>> fun1(123)
ans =
123
>> fun2()
ans =
1
Along the same lines as SCFrench's answer, but with a more C# style spin..
I would (and often do) make a class containing multiple static methods. For example:
classdef Statistics
methods(Static)
function val = MyMean(data)
val = mean(data);
end
function val = MyStd(data)
val = std(data);
end
end
end
As the methods are static you don't need to instansiate the class. You call the functions as follows:
data = 1:10;
mean = Statistics.MyMean(data);
std = Statistics.MyStd(data);
I define multiple functions in one .m file with Octave and then use the command from within the .m file where I need to make use of the functions from that file:
source("mycode.m");
Not sure if this is available with Matlab.
octave:8> help source
'source' is a built-in function
-- Built-in Function: source (FILE)
Parse and execute the contents of FILE. This is equivalent to
executing commands from a script file, but without requiring the
file to be named `FILE.m'.
You could also group functions in one main file together with the main function looking like this:
function [varargout] = main( subfun, varargin )
[varargout{1:nargout}] = feval( subfun, varargin{:} );
% paste your subfunctions below ....
function str=subfun1
str='hello'
Then calling subfun1 would look like this:
str=main('subfun1')
As of R2017b, this is not officially possible. The relevant documentation states that:
Program files can contain multiple functions. If the file contains only function definitions, the first function is the main function, and is the function that MATLAB associates with the file name. Functions that follow the main function or script code are called local functions. Local functions are only available within the file.
However, workarounds suggested in other answers can achieve something similar.
I have try with the SCFRench and with the Ru Hasha on octave.
And finally it works: but I have done some modification
function message = makefuns
assignin('base','fun1', #fun1); % Ru Hasha
assignin('base', 'fun2', #fun2); % Ru Hasha
message.fun1=#fun1; % SCFrench
message.fun2=#fun2; % SCFrench
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
Can be called in other 'm' file:
printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());
update:
I added an answer because neither the +72 nor the +20 worked in octave for me.
The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).
TL;DR
I'm looking for a way to extract a part of an existing CUDA Toolkit example and turn it into a CUDAKernel executable in MATLAB.
The Story
In an attempt to obtain a short-runtime implementation of the non-local means (NLM) 2D filter, I stumbled upon the imageDenoising example provided with the CUDA Toolkit which implements two variants of this filter, called NLM & NLM2 (or "quick NLM").
Having no previous experience with CUDA coding, I initially attempted to follow MATLAB's documentation on the subject, which resulted in several strange errors including: ptx compilation, multiple entry points and wrong number of inputs in the C prototype. At this point I realized that this isn't going to be a "just works" case and that some tinkering is required.
So I decided to eliminate the multiple entry point issue by simply deleting parts of imageDenoising.cu file and consolidating the relevant .cuh (either ..._nlm_kernel.cuh or ..._nlm2_kernel.cuh) into the .cu so as to obtain a single entry point at any given time.
To my surprise this actually managed to compile and I was finally able to create a CUDAKernel without an error (using the command k = parallel.gpu.CUDAKernel('imageDenoising.ptx', 'uint8_T *, int, int, float, float');).
This however was not enough, because I mistakenly concluded that the 1st argument is the unprocessed image in the form of an RGB matrix (i.e. X*Y*3 uint8), and so the result I was getting back was exactly the input but with 0 in the 1st 4 elements.
After searching a bit more I realized that there are additional, and critical, aspects I'm entirely unaware of (like the need to initialize __device__ variables) to such a conversion process, at which stage I decided to ask for help.
The Problem
I'm currently wondering how to efficiently continue from here. While I'd love to hear if this kind of approach can generally bear fruit (and whether a complete example of this process is available somewhere), which other pitfalls I should look out for, and what alternative courses of action I can take (considering my very limited knowledge in CUDA and the fact I won't hire anybody else to do this for me), I keep in mind that this is SO and so I must have a specific programming problem, so here goes:
How do I modify imageDenoising.cu such that the MATLAB CUDAKernel constructed from it will also accept the unprocessed image as an input?
Note: in my application, the input matrix is a 2d, grayscale, double matrix.
Related: How CudaMalloc work?
P.S.
A working piece of code would obviously be welcomed, but I'd really rather "learn to fish".
I ended up taking an alternative approach to CUDAKernel, using .MEX, by doing the following:
Setting up the external libraries OpenCV v2.4.10 (not v3!) and mexopencv.
Writing a small wrapper function for OpenCV's fastNlMeansDenoising using the guidelines of mexopencv for unimplemented functions, as seen below (excluding the documentation):
#include "mexopencv.hpp"
using namespace cv;
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
// Check arguments
if (nlhs != 1 || nrhs<1 || ((nrhs % 2) != 1) )
mexErrMsgIdAndTxt("fastNLM:invalidArgs", "Wrong number of arguments");
// Argument vector
vector<MxArray> rhs(prhs, prhs + nrhs);
// Option processing
// Defaults:
double h = 3;
int templateWindowSize = 7;
int searchWindowSize = 21;
// Parsing input name-value pairs:
for (int i = 1; i<nrhs; i += 2) {
string key = rhs[i].toString();
if (key == "h")
h = rhs[i + 1].toDouble();
else if (key == "templateWindowSize")
templateWindowSize = rhs[i + 1].toInt();
else if (key == "searchWindowSize")
searchWindowSize = rhs[i + 1].toInt();
else
mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option");
}
// Process
Mat src(rhs[0].toMat()), dst;
fastNlMeansDenoising(src, dst, h, templateWindowSize, searchWindowSize);
// Convert cv::Mat back to mxArray*
plhs[0] = MxArray(dst);
}
Compiling it..... and viola - a working CUDA-accelerated NLM filter.
The answer to my question itself can be found by comparing opencv\sources\modules\photo\src\cuda\nlm.cu (this is the opencv2 path) with imageDenoising_nlm2_kernel.cuh.
This solution worked well for me because it was more important for me to get an NLM filter running, rather than using CUDAKernel.
The main lesson I learned from this (and I'd like to pass on to others) is:
Running CUDA code in MATLAB can also be done in ways other than CUDAKernel, such as using .mex wrappers as shown above.
I have a piece of equipment that I would like to control from within Matlab on WinXP32. Its APIs are packaged in a DLL with an associated C header.
The device's API functions rely on a hardware descriptor, which is accessed by its Win32 handle and can only be directly manipulated by the API functions. From the "foo.h" header provided by the manufacturer:
typedef HANDLE BAR
#ifdef _DLL_EXPORT
#define _DLL_API __declspec(dllexport)
#else
#define _DLL_API __declspec(dllimport)
#endif
This handle is then used by the API functions, whose C signatures are of the form:
FOO_RETURN Device_Init(BAR *pbar, DWORD parameter1, ....)
Moving to Matlab, I load the library:
loadlibrary('foo','foo.h');
and the API functions are now available in Matlab. In libfunctionsview, their signatures look like:
Name Arguments
Device_Init (voidPtr, uint32, ....)
and the "foo.m" function created by loadlibrary describes them as:
fcns.name{fcnNum}='Device_Init'; fcns.calltype{fcnNum}='stdcall'; fcns.LHS{fcnNum}="uint32'; fcns.RHS{fcnNum}={'errorPtr, 'uint32', ...)
My problem is this handle "BAR". None of the following are accepted:
pbar = libpointer('BAR'); % Type was not found
pbar = libstruct('BAR'); % Undefined function or variable 'lib.BAR'
pbar = libpointer; % Segfaults when passed to DLL
Is there a way to create and manage this handle "BAR" in Matlab so that it can be used in Matlab calls to calllib('foo','command',pbar,....) ?
You can try this code to create the MATLAB pointers:
pbar = libpointer('voidPtr',[ uint8('some string') 0])
pparameter1 = libpointer('uint32',0)
and to call your DLL function use the following command:
calllib('foo','Device_Init',pbar,pparameter1,...)