4 Bouncing Ballsd仿真的加速
这个例子中使用mex函数替代了原有的函数,提高了仿真效率。
1 输入 coderdemo_setup('coderdemo_bouncing_balls');
进入软件准备好的路径环境中
2 函数内容说明
run_balls.m 函数的输入参数只有一个就是小球的个数n,n个小球,这个函数运行的过程就是模拟这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;