Matlab C代码生成 4

4 Bouncing Ballsd仿真的加速

这个例子中使用mex函数替代了原有的函数,提高了仿真效率。

1 输入 coderdemo_setup('coderdemo_bouncing_balls');

  进入软件准备好的路径环境中

2 函数内容说明

 run_balls.m 函数的输入参数只有一个就是小球的个数nn个小球,这个函数运行的过程就是模拟这n个小球的运动直到小球的初始能量被耗散殆尽,其代码为

% balls =run_balls(n)

% Given 'n'number of balls, run a simulation until the balls come to a

% complete halt(or when the system has no more kinetic energy).

function balls =run_balls(n) %#codegen

 

coder.extrinsic('fprintf');

 

%   Copyright 2010-2013 The MathWorks, Inc.

 

% Seeding therandom number generator will guarantee that we get

% precisely thesame simulation every time we call this function.

old_settings =rng(1283,'V4');

 

% The 'cdata'variable is a matrix representing the colordata bitmap which

% will berendered at every time step.

cdata =zeros(400,600,'uint8');

 

% Setup figurewindows

im =setup_figure_window(cdata);

 

% Get theinitial configuration for 'n' balls.

balls =initialize_balls(cdata, n);

 

energy = 2; %Something greater than 1

iteration = 1;

while energy> 1

    % Clear the bitmap

    cdata(:,:) = 0;

    % Apply one iteration of movement

    [cdata,balls,energy] =step_function(cdata,balls);

    % Render the current state

    cdata = draw_balls(cdata, balls);

    iteration = iteration + 1;

    if mod(iteration,10) == 0

        fprintf(1, 'Iteration %d\n',iteration);

    end

    refresh_image(im, cdata);

end

fprintf(1,'Completed iterations: %d\n', iteration);

 

% Restore RNGsettings.

rng(old_settings);

3 生成MEX函数

输入命令

codegen run_balls-args0

其中-args0表示double类型数据,就是说生成的代码的输入是一个和0一样的double数据。

尽管这个函数实际上还在运行过程中调用了其它函数,但是在生成的时候,你只需要对这个函数进行生成处理

你可以比较一下效率

tic, run_balls(50); t1 = toc;

tic, run_balls_mex(50); t2 = toc;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值