C code not working inside MATLAB System

4 views (last 30 days)
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

Accepted Answer

Ryan Livingston
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
Ryan Livingston
Ryan Livingston on 12 Apr 2016
Glad to hear it, that's a hard error to track down.

Sign in to comment.

More Answers (0)

Categories

Find more on Deployment, Integration, and Supported Hardware in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!