How to access an array of structs in simulink? - matlab

I have the problem, that I have to access a funktion form a dll in matlab/Simulink in the rtw.
This should work with a s function, but I have the needed parameters in a array of structures organized.
The question is now how I can reach them when I want to call my DLL function?
Or is there a better way (e.g. level 2 Matlab files or something similar)?
The pure simulation (without RTW) worked pretty well with level 2 m files but I am not able to write a tlc file for compiling them. I did not find much on the net and the documentation only about C sources.
Thanks
Christian

For signals in Simulink, what you are asking for is an array of buses. There is similar support for using arrays of structs for parameters. For calling an external function, you might want to look at the legacy code tool. You might also be able to use the MATLAB function block to call your external dll.

In addition to what #MikeT says:
Generating code from Level 2 M-S-Functions is problematic. Read this: http://www.mathworks.co.uk/help/toolbox/simulink/sfg/f7-67622.html#brgscav-1
Also, M-S-functions are generally slow, because they run in the MATLAB interpreter: http://blogs.mathworks.com/seth/2010/10/28/tips-for-simulation-performance/

In the end I coded the problem in C and used an array where I defined to order of the elements. Then I wrote some interface functions to access this "virtual" struct.
This is not very good coding but the easiest way I have found and it is portable.
Thanks

Related

How to force Matlab/Simulink Coder to use the parameters created in simulink

I have a simulink model using matlab function blocks.
When i try to generate the C code from my model, the structures parameter scopes i used to represent my data are unused :
When i say unused i mean,
matlab coder creates a header file with all my structures defined.
but in the actual algorithms, when the structure should be sent as argument to a function, matlab coder just defines new variables for each of the fields of which values are hardcoded.
So something like : Function(parameter); with parameter contraining X = 5 and Y = 8 becomes Function(5,8); once generated (so the function definition creating new variables for each of the fields).
You can imagine how messy that gets once the structures get too big.
A friend of mine told me objects dont work with matlab coder. So replacing my structs with objects is not an option unless my friend was wrong.
Does anyone know how i could force matlab coder to actually use the structures i defined for him?
Or maybe there is another solution that i did not think of?
Thanks!
I have found the answer to my own question.
In the configuration file of the code generation, under "Optimization" tab, change "default parameter behaviour" from 'inlined' to 'tunable'.
I hope this will help others :)

How to keep program data in different m files in matlab

I want to write a modular matlab program and I have some data structures such as history in my program. Is that true that I have to keep all my data-structures in the main script of my program? In other words if I have some arrays and fields of data, if I put them in other m files, such as functions, they are temporal and they are going to be collected as garbage in my program execution. I am a java developer and now I want to develop some code in matlab.
As Tommaso suggested in a comment, you should use classes. Look at the documentation for classdef to get started. The full documentation to create classes starts at this page.
But to directly answer your question: it is possible to store static data in functions: see persistent.
If you're making a GUI, there are built-in ways to store data, see guidata.
Finally, there is also getappdata and setappdata, which set global variables but specific to one app.
For all that's good in this world, don't use global, it's not worth the hassle, here are plenty of better alternatives.
PS: if the links here break, note that it is always possible to type help <cmd> to get help on one of the functions mentioned here.

Static Variables in Simulink S-Function Builder

I am currently working on the implementation of some C-Code in a Simulink model using the S-Function Builder block.
The code uses various timers and counters, which are defined as static variables to enable the access to the data in following simulation steps.
However, if I start the simulation MATLAB crashes without error message ('Fatal Exception'). To test I defined the variables without the 'static' statement. The Simulation works in this case, however with (logically) wrong results of the S-Function.
Has anybody else faced similar issues or knows how to declare static variables in Simulink?
P.S.
I know I could use Work Vectors, which I do not intend to do, since it would result in huge efforts in adopting the function to do so.
Furthermore I could simply build a feed-back loop in the model using a memory block. For approximately 100 variables this solution would also be pretty impractical.
Not a solution, but a possible workaround is to use the coder.ceval functionality. I have used this to wrap a C-function with similar (static variables used as counters) function. The coder.ceval call is then placed in an embedded matlab block. Possibly some definitions of the interfaces must also be made (structures / bus objects).
Check coder.ceval, coder.rref and coder.wref for the call structure.
It seems like it was a bug in Simulink or the MinGW Compiler. However I tore down the code, ending up with it crashing with the call of one specific variable. I renamed the variable, since I could not find any error in the syntax. Now everything works fine...
The variable name had various underscores and capital letters - in case anyone makes similar experiences.

MATLAB organise external toolboxes or turn them into packages to prevent shadowing

I'm working on a large data analysis that incorporates lots of different elements and hence I make heavy use of external toolboxes and functions from file exchange and github. Adding them all to the path via startup.m is my current working method but I'm running into problems of shadowing function names across toolboxes. I don't want to manually change function names or turn them into packages, since a) it's a lot of work to check for shadowing and find all function calls and more importantly b) I'm often updating the toolboxes via git. Since I'm not the author all my changes would be lost.
Is there programmatic way of packaging the toolboxes to create their own namespaces? (With as little overhead as possible?)
Thanks for the help
You can achieve this. Basic idea is to make all functions in a private folder and have only one entry point visible. This entry point is the only file seeing the toolbox, and at the same time it sees the toolbox function first regardless of the order in the search path.
toolbox/exampleToolbox.m
function varargout=exampleToolbox(fcn,varargin)
fcn=str2func(fcn);
varargout=cell(1,nargout);
[varargout{:}]=fcn(varargin{:});
end
with toolbox/exampleToolbox/private/foo.m beeing an example function.
Now you can call foo(1,2,3) via exampleToolbox('foo',1,2,3)
The same technique could be used generating a class. This way you could use exampleToolbox.foo(1,2,3)

How to invoke a matlab function from mathematica?

I would like to call a matlab function from mathematica. How best to do that?
I have found an ancient post on Wolfram site describing a way to do this, is this still the way to connect the two?
You can try NETLink for this at least under Windows:
In[1]:= Needs["NETLink`"]
matlab = CreateCOMObject["matlab.application"]
Out[2]= «NETObject[COMInterface[MLApp.DIMLApp]]»
And then you can invoke Matlab functions:
In[4]:= matlab#Execute["version"]
Out[4]= "
ans =
7.9.0.529 (R2009b)
"
In[5]:= matlab#Execute["a=2"]
matlab#Execute["a*2"]
Out[5]= "
a =
2
"
Out[6]= "
ans =
4
"
HTH
You can use mEngine. The precompiled Windows MathLink executable works with Mathematica 8. On Windows you may need to add MATLAB to the system path.
The advantage of this compared to the NETLink method is that transferring variables between Mathematica and MATLAB will be as easy as mGet["x"] or mPut["x"]. Although this might be possible with NETLink too, the advantage of mEngine is that you don't need to implement it yourself (which is great if like me you don't know anything about COM or .NET)
I would imagine that this is a difficult problem in general, but can be easily solved with a little programming for a particular case. I'll demonstrate with C#.
I would build a string of calls, like so.
Mathematica calls a C# program, through MathLink. This is near trivial to setup, and Mathematica has a sample project in Mathematica\8.0\SystemFiles\Links\NETLink directory.
C# program calls Matlab. There are several ways to make this call, and this handy link describes how to do it and offers sample code.
C# program returns Matlab results.
All in all I could do this in less than 50 lines of C# code, for a specific problem. Not too much work, in other words. Possible problems are data conversion, but if you want to send back and forth arrays of data, MathLink offers a lot out of the box. Similarly Mathematica can be linked to MATLAB through Java, though I haven't done that myself.
Perhaps the easiest connection could be made through Python. Mathematica offers an installable MathLink python library, located at Mathematica\8.0\SystemFiles\Links\NETLink, and Matlab has an addon library called PyMat, which can be downloaded here, but this package hasn't been maintained for a long time and supports only the most ancient of Matlabs.
Alternatively you can forgo Matlab altogether in favor of SAGE and/or numpy.
There is now a new package for this --- MATLink. It is the most complete such package I am aware of. (Disclaimer: I'm one of the developers of MATLink.)
MATLink lets you ...
seamlessly call MATLAB functions form Mathematica
transfer data between the two systems
Most MATLAB data types are supported, including sparse arrays, structs and cells.
A more complete description is available here. For detailed examples, see the website.