您的位置:首页 > 编程语言 > MATLAB

Matlab C代码生成 2

2016-07-03 19:01 309 查看

2 滑动平均滤波器

将一个滑动平均滤波器的m代码转换为c代码,要经过如下步骤
(1) Add the %#codegen directive to the MATLAB function toindicate that it is intended for code generation. This directive also enablesthe MATLAB code analyzer to identify warnings
and errors specific to MATLAB forcode generation.
添加%#codegen标志到Matlab函数中,表明这个函数要用来生成C代码。
(2) Generate a MEX function to check that theMATLAB code is suitable for code generation. If errors occur, you should fixthem before generating C code.
 生成一个mex函数之前你应当检查一下是否原来的代码存在错误。如果其中存在导致不能转化为MEX的错误,那么应当在生成C代码前解决掉。
(3) Test the MEX function in MATLAB to ensure that it isfunctionally equivalent to the original MATLAB code and that no run-time errorsoccur.
测试这个MEX函数确保它和原来的代码意图一致,并且确定其中没有运行时间错误出现
(4) Generate C code
生成C代码。
(5) Inspect the C code.
检查C代码。
 
开始介绍:
看一下代码:
% y = averaging_filter(x)

% Take an input vector signal 'x' and produce an output vector signal 'y' with

% same type and shape as 'x' but filtered.

function y = averaging_filter(x) %#codegen

% Use a persistent variable 'buffer' that represents a sliding window of

% 16 samples at a time.

persistent buffer;

if isempty(buffer)

    buffer = zeros(16,1);

end

y = zeros(size(x), class(x));

for i = 1:numel(x)

    % Scroll the buffer

    buffer(2:end) = buffer(1:end-1);

    % Add a new sample value to the buffer

    buffer(1) = x(i);

    % Compute the current average value of the window and

    % write result

    y(i) = sum(buffer)/numel(buffer);

end

这个函数编写的不错,尤其是其中对size,class和numel的运用,再者就是对滑动的实现都很强大。
注意到%#codegen 标志已经添加到函数命名的那行。
 
产生一些采样数据,代码如下(是一个添加了噪声的数据)
v = 0:0.00614:2*pi;

x = sin(v) + 0.3*rand(1,numel(v));

plot(x, 'red');

产生用来测试的MEX文件
codegen averaging_filter-args{x}

其中the '-args' command-line option supplies an example input so that 'codegen' can infer new types based on the input types

就是说-args{x} 使得函数可以根据输入的数据类型自行生成输出的数据类型。

生成C代码
codegen -configcoder.config('lib')averaging_filter-args{x}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: