C code not working inside MATLAB System
2 views (last 30 days)
Show older comments
Carlo Savorgnan
on 12 Apr 2016
Commented: Ryan Livingston
on 12 Apr 2016
I'm trying to interface some C code inside a MATLAB system derived class. The C function I want to use multiplies by 3 the input argument. File "triple.h":
#ifndef __TRIPLE_H__
#define __TRIPLE_H__
#ifdef MATLAB_MEX_FILE
#include <tmwtypes.h>
#else
#include "rtwtypes.h"
#endif
double triple(double in);
#endif
File "triple.c":
#include "triple.h"
double triple(double in)
{
return in*3;
}
I defined a MATLAB function "call_triple" so that I can call the C function. File "call_triple.m":
function out = call_triple(in)
%#codegen
assert(isa(in, 'double'));
if coder.target('MATLAB')
out = call_triple_mex(in);
else
out = double(0.0);
out = coder.ceval('triple', in);
end
I compiled with the MATLAB coder "call_triple" to obtain "call_triple_mex":
>> codegen -config:mex call_triple triple.h triple.c
Now I can use call_triple from MATLAB command line:
>> call_triple(2.4)
ans =
7.2000
Finally I implemented the class "triple_system"
classdef triple_system < matlab.System & coder.ExternalDependency
...
... more code
...
function out = stepImpl(~, in)
out = call_triple(in);
end
...
... more code
...
The class works from the command line:
>> obj = triple_system;
>> step(obj, 3.2)
ans =
9.6000
The problem arises when I use the class inside a "Matlab system" block inside Simulink and I select the option "Simulate using: code generation". The output of the Simulink block returns a number which makes no sense to me (like 1689233153 or similar big numbers). The block works fine when I select: "Simulate using: interpreted execution".
What am I doing wrong? I wold expect the same behaviour from the two simulation methods.
Thanks
Carlo
0 Comments
Accepted Answer
Ryan Livingston
on 12 Apr 2016
You likely need to add coder.cinclude('triple.h') in the System Object to include the header for triple. Without the declaration of triple, the C compiler assumes that the signature is int triple(int) which results in the unexpected behavior that you are seeing.
2 Comments
More Answers (0)
See Also
Categories
Find more on Naming Conventions in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!