Basic networking with Matlab Coder - matlab

I'm trying to get very basic network functionality with Matlab Coder (I need to turn it into C code). However, all the network classes and objects I try arn't supported by Coder. It seems unreasonable that Matlab would completely neglect networking entirely with this tool. Is there some method of sending data over a network that DOES work with coder?
I'd prefer TCP, but UDP or anything else that will actually send/receive data will work, as long as it is compatible with Coder.

This answer assumes that the DSP System Toolbox is not available. If it is, the System Objects dsp.UDPSender and dsp.UDPReceiver may be considered.
Since the final goal is to generate C code, and because network I/O is usually done via a library, a good approach would be to integrate external C code that does the network I/O into your MATLAB Code. The basic way to call an external C function is using coder.ceval and the process is explained here.
Recommended Steps
Write C(++) functions implementing the behaviour you need or find a C library providing the necessary functionality. Assume we implement the function externalUDPSend in the files externalUDPSend.h/.c.
Write one or more MATLAB functions that call your C(++) functions using coder.ceval as shown in the linked documentation. These will serve as a wrapper around your external code, and will expose the C(++) code to MATLAB. Something like callfoo in the linked example will work:
function y = useExternalUDP(x)
%#codegen
if coder.target('MATLAB')
% Running in MATLAB. Use standard MATLAB
% network I/O code here
...
else
% Generating code. Call external code/library
% Include header for external code
coder.cinclude('externalUDPSend.h');
% Set the type of the output. Assume double scalar
% Change the RHS to match the return type
y = 0;
y = coder.ceval('externalUDPSend',x,numel(x));
end
Develop your project. Call the wrapper function(s), which will work in MATLAB and in the generated code because of the use of coder.target.
Generate a MEX function using something like:
codegen useExternalUDP -config:mex externalUDPSend.c -args ...
The generated MEX function serves as the MATLAB interface to your custom code so there is no need to hand write a MEX interface. MATLAB Coder will generate all of MEX interfacing logic for you. Then test that MEX function in MATLAB. Testing the MEX function is important because runtime errors like out of bounds indexing, using features not supported for code generation, etc. can be detected and reported in MEX. These checks are removed from generated standalone code.
Generate standalone code and either let MATLAB Coder compile it to a library or deploy the code to an external IDE and compile it there.
Integrating External Libraries/Encapsulating Dependencies
Note that you may also need to link in libraries if you choose to use an existing network I/O library, or you may need to modify the build of the generated code. You can either use coder.updateBuildInfo or coder.ExternalDependency to achieve this in your MATLAB Code.
Further Reading
The file reading example shows some more advanced custom code integration tools such as coder.ref, coder.opaque, and dealing with C strings from MATLAB code when calling external code. Note that the MATLAB functions fprintf and fread are supported for code generation so this example is meant to be instructive rather than a necessity for doing file I/O.

If you have the DSP System Toolbox, the System Objects dsp.UDPSender and dsp.UDPReceiver are supported for code generation since they are listed in the comprehensive list of supported functions.
The code generated from them relies on prebuilt libraries shipped with MATLAB and will run on desktop platforms compatible with those libraries. See the documentation for the UDP Receive block for more details.

Related

Compile Matlab generated C source code on a Linux platform to created a Linux MEX

I have a Windows Matlab R2020a and was able to generate C source code for my Matlab function. However, I need to run a MEX file (for speed) on a Linux platform which has a Matlab installed (without Coder) and no way to install it (even trial version).
Please, provide the steps to compile this Matlab-generated C code on the linux (Ubuntu) system. I guess it can be done with gcc. I am unable to find a clear description on the web, as this process seems extremely complicated due to the obscure command line args needed to give to gcc (and i only rarely compile C code).
Please, note that generating C code using the MATLAB Coder App is not enough if you need a MEX file. MEX files have to contain a mexFunction function, which is not generated by the Coder App.
As a first step, I'd make sure your compiler is supported by MATLAB for the creation of MEX files. You can find the supported compilers on Linux here. Then I'd check whether the compiler is setup for Matlab to use it, as shown here. Finally, I'd have a look at some examples provided by Mathworks themselves: here
Once the C code (with the mexFunction) is ready, you can compile it using the mex command and use it on the Linux platform with no or minimal adjustments, depending on how heavily you rely on the functions defined in mex.h (which is the header your C file will have to import if you want to generate a MEX file).
You need the interface provided by the mexFunction for Matlab to be able to exchange inputs and outputs with the compiled function. Note that you can create other standard C functions (possibly defined in other C files) and call them from within the mexFunction as you would normally do in C. Basically, you can create your own libraries in C and then use them in Matlab via dedicated mexFunctions.
mex.h also provides the API to "convert" C data structures into Matlab data structures (e.g. arrays, cell arrays etc., all via the mxArray type).
There's a bit of a learning curve, mostly spent in understanding how to convert data back and forth between standard C and Matlab, but it's certainly worth your while. With a bit of care (e.g. switching to mxArray types only when absolutely necessary), you can end up having libraries of functions that can be used in standard C programs as well as in Matlab applications

Alternatives to extrinsic functions such as imread and other functions during code generation in MATLAB

As you may know, extrinsic functions are not outputted during the code generation process. Are there alternatives to these functions and/or solutions to this problem? My code generation error report is shown below :
Code Generation Error Report
I am surprised that I can't output size and rgb2gray either. Since these are essential to my program, I cannot avoid them.
Help will be much appreciated!
This is a good question, and I see similar questions fairly frequently. As I started using MATLAB Coder, one of the biggest pitfalls was the constant search for supported functions. I sympathize with your frustration, and I have a few tips, having been through this.
First, to your direct question, while imread isn't supported by Coder, size and rgb2gray are. Probably Coder is complaining about these because they have been passed mxArrays from the call to imread, which is fine when it is extrinsic, but not ok for separate generation. That's just a guess. A very useful tool in writing code is the list of Coder supported functions: List of Functions supported in MATLAB Coder
But even with those two, to replace imread is not a tiny task. You'll have to find another library that supports the particular file you're working with, and then stitch that in using coder.ceval. Alternatively, if you can find a pure MATLAB implementation of it, that might help.
Are you targeting a pure C library or a MEX file? If you intend to use this code within the MATLAB environment, you can always use imread separately and then pass the data.
And now to some more general observations: MATLAB Coder isn't a perfect MATLAB to C translation system. It's extremely powerful, and I've been able to write some very large projects with it, but if what you want is the ability to run any MATLAB code without MATLAB around, you should look at MATLAB Compiler, a different add-on. There's a very good Q and A about this here: MATLAB Compiler vs MATLAB Coder
When writing projects in MATLAB Coder, it's really best to start from scratch, knowing you're targeting C code ultimately. There are so many gotchas in the conversion from MATLAB to C that you have to be always vigilant while writing the MATLAB code.
One tool that helps is to right-click on a file in the "Current Folder" list that usually resides on the left-side of the main window, and select "Check Code Generation Readiness." You'll get a great report of potential problems in the file. I recommend using this often.
Another useful tool is to always put the %#codegen tag into your code. This alerts the MATLAB editor that the .m file is intended for code generation, so it provides extra context-sensitive information while you're writing the file. This helps enormously.
The most commonly missing functions for code generation are file IO functions. There are some good reasons for this, but it's frustrating nonetheless.
When you stitch in external C code, you use the coder.ceval function, which can provide excellent access to external libraries. Using this well is a whole other topic, outside the scope of this question.
If you can indicate exactly what kind of files you're interested in reading (PNG, BMP, TIFF, etc.) perhaps someone may be able to identify a good external library for you to use.

How can I use matlab source code in labview without matlab?

I found mathscript can do this,but it seem too slow.
So I want to use matlab to create a dll file used by labview,but all information I can find just how dll could used in C++,but C++ also must use the .lib file ,I am concerned labview could not use lib. file.
So can I use the .dll in labvew,and how?Is there anyother way to use matlab source code in labview without matlab?
You will need to purchase the MATLAB Compiler which is quite expensive unless you are a student.
You can also call the MATLAB application (if it's installed) using the MATLAB Script Node (which is different than Mathscript) - see here
Another alternative is Python's Numpy which I personally picked up quickly coming from a MATLAB background. If you want to go down that route I can give you further advice on how to integrate with LabVIEW.

Will Matlab standalone be faster than Matlab from UI for long execution code?

I have built an standalone Matlab application. I was expecting it to be faster than running the application from the Matlab environent but it is indeed a bit slower (1.3 seg per iteration vs 1.5 seg per iteration)
I am not counting the init time required by MCR but the execution of my code.
Is that the expected performance or should I be obtaining a performance improvement?
I haven't found any settings on the deployment tool that could help to reduce execution time.
Thanks in advance
Applications built with MATLAB Compiler should execute at pretty much exactly the same speed as within MATLAB.
MATLAB Compiler does not convert your MATLAB code into machine code in the same way as a C compiler does for C. What it does is to archive and encrypt your MATLAB code (note, it properly encrypts it, not just pcodes it as a comment suggests), create a thin executable wrapper and package them together, possibly also with MATLAB Compiler Runtime (MCR). MCR is very similar to MATLAB itself, without a graphical user interface, and is freely redistibutable.
When you run the executable, it dearchives and decrypts your MATLAB code and runs it against the MCR. It should run exactly the same, both in terms of results and speed.
Very old versions of MATLAB Compiler (pre-version 4.0) worked in a different way, converting a subset of the MATLAB language into C code, and compiling this. This provided a potentially significant speed-up, but only a subset of the language was supported and results, unless you were careful, could sometimes be different. Similar functionality is now available in the separate MATLAB Coder product.
There are a few small things you can do to improve performance: for example, within deploytool you can specify which toolboxes your application uses. deploytool uses a dependency checker to package up all MATLAB functionality that it thinks your code might possibly depend on, but it can't always tell exactly, as the functions your code needs might change at runtime. It therefore errs on the side of caution and includes more than necessary. By specifying only the toolboxes you know to be necessary, you can speed things up a little (it also speeds up the build process quite a bit).

Can anyone with access to the new "Matlab Coder" product show some output of the translation to C?

Matlab Coder is a recently released MathWorks product. My understanding is that it is a Matlab-to-C compiler with the biggest advantage over previous solutions being that the resulting program does not need to be linked against a Matlab shared library.
Can someone with access to this product confirm the above? What are the dependencies of the translated programs and what kind of performance are we talking about? Also I would really like to see some example outputs, to know if the resulting C programs can be understood and improved without access to the Matlab source.
If done right this could be very powerful, allowing rapid prototyping in Matlab and instantaneous conversion to C when things are getting serious. I kind of whish it doesn't work well so that Python+Numpy+Scipy.weave is still superior ^^.
MATLAB Coder can allocate memory using malloc, so you can generate C code from MATLAB functions that operate on dynamically sized data. You can also choose the option of static allocation with a maximum size for variables.
RE: using BLAS for matrix multiplication – while the generated C code doesn’t automatically include any processor/platform specific optimizations, there is a feature called Target Function Library, which that allows users to write their own implementation of primitive operations (such as matrix multiplication), and include them in the generated code. You can hook up BLAS libraries to MATLAB Coder via that method. There’s also an ability to include optimized processor specific calls for larger functions through custom code integration and conditional compilation that lets you specify one set of code to use for code generation, and another set for simulation (for example, an optimized FIR function for an Texas Instruments DSP and functionally equivalent code for simulation that can execute on your PC written in C or in MATLAB).
Hope this is helpful --
Arvind Ananthan; Product Manager for MATLAB Coder; MathWorks
I am using Matlab Coder with Real Time Workshop (RTW) in order to generate self standind standard C code.
First of all you are asked to use a Matlab subset called "Embedded Matlab" you can find the doc about it on the web
You also have to avoid any dynamic exploitation of variables and you can't obviously generate c code for plots or figures.
The code it generates could be a mess to understand but it works.
you should actually not try to understand it. In a certain way it is as you would try to understand the assembler your compiler generates from a C code you wrote, quite pointless.
another thing you should take care of is to declare persistent big data types (vectors, big arryes, etc.) otherwise they will be allocated into your stack...
good luck!