MATLAB Answers

converting m-file to c-code

85 views (last 30 days)
Nalla on 22 Feb 2011
Edited: Walter Roberson on 19 Jan 2017
Hello all. Iam trying to covert m-file into a c-code so that it can be used in microprocessor for real-time implementation. Iam following two methods: 1-Using embedded matlab simulink block. 2-Using emlmex and emlc commands.
When i use the first method, an error occured "cannot generate c-file" Here is the matlab code which is on extended kalman filter:
% position measurement noise (feet)
MeasNoise = 10;
accelnoise = 0.2; % acceleration noise (feet/sec^2)
a = [1 dt 0; 0 1 0; 0 0 1]; % transition matrix
b = [dt^2/2 0; dt 0; 0 dt]; % input matrix
c = [1 0 0; 0 0 1]; % measurement matrix
x = [0; 0; 0]; % initial state vector
xhat = x; % initial state estimate
Sz = [MeasNoise^2 0; 0 MeasNoise^2]; % measurement error covariance
Sw = [10^-6 0 0; 0 4*10^-4 0; 0 0 0.05]; % process noise cov
P = Sw; % initial estimation covariance
% Initialize arrays for later plotting.
pos = []; % true position array
poshat = []; % estimated position array
posmeas = []; % measured position array
vel = []; % true velocity array
velhat = []; % estimated velocity array
angle = [];
anglehat = [];
anglemeas = [];
for t = 0 : dt: duration,
% Use a constant commanded acceleration of 1 foot/sec^2.
u = [1;4*dt];
% Simulate the linear system.
ProcessNoise = accelnoise * [(dt^2/2)*randn; dt*randn; dt*randn];
x = a * x + b * u + ProcessNoise;
% Simulate the noisy measurement
MeasNoise = [0.5*randn; 0.5*randn]
y = c * x + MeasNoise;
% Extrapolate the most recent state estimate to the present time.
xhat = a * xhat + b * u;
% Form the Innovation vector.
Inn = y - c * xhat;
% Compute the covariance of the Innovation.
s = c * P * c' + Sz;
% Form the Kalman Gain matrix.
K = a * P * c' * inv(s);
% Update the state estimate.
xhat = xhat + K * Inn;
% Compute the covariance of the estimation error.
P = a * P * a' - a * P * c' * inv(s) * c * P * a' + Sw;
% Save some parameters for plotting later.
pos = [pos; x(1)];
posmeas = [posmeas; y(1)];
poshat = [poshat; xhat(1)];
vel = [vel; x(2)];
velhat = [velhat; xhat(2)];
angle = [angle; x(3)];
anglemeas = [anglemeas; y(2)];
anglehat = [anglehat; xhat(3)];
% Plot the results
close all;
t = 0 : dt : duration;
plot(t,pos, t,posmeas, t,poshat);
xlabel('Time (sec)');
ylabel('Position (feet)');
title('Figure 1 - Vehicle Position (True, Measured, and Estimated)')
plot(t,angle, t,anglemeas, t,anglehat);
xlabel('Time (sec)');
title('Figure 1 - Vehicle orientation (True, Measured, and Estimated)')
plot(t,pos-posmeas, t,pos-poshat);
xlabel('Time (sec)');
ylabel('Position Error (feet)');
title('Figure 2 - Position Measurement Error and Position Estimation Error');
plot(t,vel, t,velhat);
xlabel('Time (sec)');
ylabel('Velocity (feet/sec)');
title('Figure 3 - Velocity (True and Estimated)');
xlabel('Time (sec)');
ylabel('Velocity Error (feet/sec)');
title('Figure 4 - Velocity Estimation Error');
This code is first converted into embedded matlab and then converted into c-file. Can anyone help me out. Thanks alot..!


Kaustubha Govind
Kaustubha Govind on 22 Feb 2011
I'm guessing the error occurs because you use functions like PLOT, that are not supported for code generation.
Guillermo Soriano
Guillermo Soriano on 23 Jan 2013
Hi: among function plot, there are others, but the most important is that your code must start with function, otherwise can not be converted to c
Walter Roberson
Walter Roberson on 23 Jan 2013
That was true in the timeframe that the question was asked, but I have seen hints (and a very brief mention in the documentation) that some of the newer MATLAB versions permit scripts to be compiled.

Sign in to comment.

Accepted Answer

Gautam Vallabha
Gautam Vallabha on 22 Feb 2011
If you just want to convert MATLAB code to C code, you don't need to create a Simulink block. You can just create a MATLAB function file and invoke emlc. Make sure that:
  1. Your MATLAB function has %#eml at the beginning
  2. Your MATLAB function only uses functions and features from the Embedded MATLAB subset. In particular, graphics functions like figure, xlabel, and plot are not supported; you can have them in your file, but then you should use eml.extrinsic to tell EMLC to ignore these functions.
  3. Pay careful attention to the datatypes of the functions inputs
function z = testeml(x, y)
% datatypes and sizes of inputs
assert( isa(x, 'single') && isa(y, 'single') );
assert( all(size(x) == [1 10]) && all(size(y) == [1 10]) );
% functions that EMLC should ignore
eml.extrinsic('figure', 'plot');
z = x .* y;
You can compile this with:
config = emlcoder.RTWConfig;
config.GenCodeOnly = true;
config.GenerateReport = true;
emlc -s config testeml
You can also run it directly from the MATLAB command line:
>> testeml(single(1:10), single(2:2:20))


Nalla on 1 Mar 2011
error appearing:
0 304 C:/Users/DELL/Documents/gyrokall.c/ss.c:14: error: Can't open include file "norm.h",randn.h,ekf.h,rt_nonfinite.h
Kaustubha Govind
Kaustubha Govind on 1 Mar 2011
It appears that these header files are not on the include path. I'm not familiar with the microC environment, but you should ensure that the location of these headers is added to the list of include directories for your project. If you are compiling from command-line, this typically means adding "-I /path/to/headers" to the compile command.
Nalla on 3 Mar 2011
I have compiled the .m file in matlab environment without any errors.
Now i am trying to get an hex file from the .c file(generated from matlab)so that i can use it in micro-controller.Are there any other ways of getting hex file?

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 3 Mar 2011
Here is a function to convert any input file in to a hex format. As I had no idea what a "hex file" for whatever micro controller you are using looks like, I used a common hex dump format.
function write_as_hex(infile, outfile)
fin = fopen(infile, 'r');
if fin < 0
warning('failed to open input file, no output');
fout = fopen(outfile, 'w');
if fout < 0
warning('failed to open output file, no output');
indata = fread(fin);
trailbytes = mod(length(indata), 16);
fprintf(fout, [repmat('%2X ',1,15) '%2X\n']), ...
fprint(fout, [repmat(%2X ',1, trailbytes-1) '%2X\n'], ...


Show 6 older comments
Nalla on 7 Mar 2011
hi..can i use mplab to convert my .m or .c file into hex file..?
Walter Roberson
Walter Roberson on 7 Mar 2011
You can use one of the Mathworks tools to convert your embedded Matlab to C. Then, as best I can tell from the documentation, you can use mplab to convert the C file into executable code in .HEX format suitable for downloading to the PIC processor.
Nalla on 8 Mar 2011
thank Q

Sign in to comment.

Sign in to answer this question.