Main Content

Use Generated Code to Accelerate an Application Deployed with MATLAB Compiler

此示例显示如何使用生成的代码加速使用MATLAB®Compiler™部署的应用程序。该示例通过使用MATLAB®Coder™生成算法的MEX版本来加速算法。它使用MATLAB编译器部署调用MEX函数的独立应用程序。已部署的应用程序使用MATLAB®运行时,该运行时使免版税部署到没有MATLAB的人。

此工作流程是有用的:

  • You want to deploy an application to a platform that the MATLAB Runtime supports.

  • 该应用程序包括一种适用于代码生成的计算密集型算法。

  • The generated MEX for the algorithm is faster than the original MATLAB algorithm.

  • 您无需部署应用程序的可读C / C ++源代码。

The example application uses a DSP algorithm that requires the DSP System Toolbox™.

Create the MATLAB Application

为了加速,它是一种从调用它的代码中分离计算密集型算法是最好的做法。

In this example,myRLSFilterSystemIDSim实现算法。myrlsfiltersystemidapp.provides a user interface that callsmyRLSFilterSystemIDSim.

myRLSFilterSystemIDSimsimulates system identification by using recursive least-squares (RLS) adaptive filtering. The algorithm usesdsp.variaseBandWidthfirfilter.to model the unidentified system anddsp.RLSFilterto identify the FIR filter.

myrlsfiltersystemidapp.provides a user interface that you use to dynamically tune simulation parameters. It runs the simulation for a specified number of time steps or until you stop the simulation. It plots the results of the simulation on scopes.

For details about this application, see系统识别使用RLS自适应滤波in the DSP System Toolbox documentation.

In a writable folder, createmyRLSFilterSystemIDSimmyrlsfiltersystemidapp.. Alternatively, to access these files, clickOpen Script.

myRLSFilterSystemIDSim

功能[tfe,err,cutoffFreq,ff] =......myrlsfiltersystemidsim(凹部)%myrlsfiltersystemidsim实现了所用算法%myrlsfiltersystemidapp。%此功能通过系统实例化,初始化和步骤% objects used in the algorithm.%% You can tune the cutoff frequency of the desired system and theRLS通过出现的GUI忘记RLS过滤器的折射率%myrlsfiltersystemidApp已执行。% Copyright 2013-2017 The MathWorks, Inc.%#codegen.%实例化和初始化系统对象。声明对象% persistent so that they are not recreated every time the function is% called inside the simulation loop.persistentRLSFILT SINE Unknownsys TransferfunctionSimatorifisempty(rlsFilt)% FIR filter models the unidentified systemunknownSys = dsp。VariableBandwidthFIRFilter ('SampleRate',1e4,......'filterorder',30,......'CutoffFrequency',.48 * 1e4/2);% RLS filter is used to identify the FIR filterrlsFilt = dsp.RLSFilter('忘记事实',.99,......'长度',28);用于生成输入信号的%正弦波sine = dsp.SineWave('SamplesPerFrame',1024,......'SampleRate',1e4,......'频率',50);用于估计频率响应的%转移功能估计% FIR and RLS filters.TransferFunctionestimator = DSP.TransferFuncesseTimator(......'FrequencyRange','中心',......'SpectralAverages',10,......'FFTLengthSource','Property',......'FFTLength',1024,......'Window','Kaiser');endiftuningUIStruct.Reset% reset System objectsreset(rlsFilt); reset(unknownSys); reset(transferFunctionEstimator); reset(sine);end%tune冷杉截止频率和遗忘因子iftuningUIStruct.ValuesChanged param = tuningUIStruct.TuningValues; unknownSys.CutoffFrequency = param(1); rlsFilt.ForgettingFactor = param(2);end% Generate input signal - sine wave plus Gaussian noiseinputSignal = sine() + .1 * randn(1024,1);%滤波器输入虽然冷杉滤波器desiredOutput = unknownSys(inputSignal);% Pass original and desired signals through the RLS Filter[rlsOutput , err] = rlsFilt(inputSignal,desiredOutput);%制备传输功能估计器的系统输入和输出inChans = repmat(inputSignal,1,2); outChans = [desiredOutput,rlsOutput];%估计传递函数TFE = TRANSIFEC功能QUANTERIMATOR(INCHANS,OUTCHANS);% Save the cutoff frequency and forgetting factorcutofffreq = Unknownsys.Cutofffrequency;ff = rlsfilt.forgettingfactor;end

myrlsfiltersystemidapp.

功能scopeHandles = myRLSFilterSystemIDApp(numTSteps)% myRLSFilterSystemIDApp initialize and execute RLS Filter% system identification example. Then, display results using% scopes. The function returns the handles to the scope and UI objects.%% Input:% numTSteps - number of time steps% Outputs:% scopeHandles - Handle to the visualization scopes% Copyright 2013-2017 The MathWorks, Inc.ifnargin == 0 numTSteps = Inf;%运行直到用户停止仿真。end%创建范围tfescope = dsp.ArrayPlot('plottype','Line',......'Position',[8 696 520 420],......'YLimits',[-80 30],......'SampleIncrement',1e4/1024,......'ylabel','Amplitude (dB)',......'xlabel','Frequency (Hz)',......'Title','Desired and Estimated Transfer Functions',......'ShowLegend',真的,......'xoffset',-5000); msescope = timescope('SampleRate',1e4,......'Position',[8 184 520 420],......'TimeSpanSource','property','TimeSpan',0.01,......'YLimits',[-300 10],'ShowGrid',真的,......'ylabel','Mean-Square Error (dB)',......'Title','rlsfilter学习曲线');screen = get(0,'ScreenSize');outerSize = min((screen(4)-40)/2, 512); tfescope.Position = [8, screen(4)-outerSize+8, outerSize+8,......outerSize-92]; msescope.Position = [8, screen(4)-2*outerSize+8, outerSize+8,......outerSize-92];%创建UI以调整FIR滤波器截止频率和RLS过滤器% forgetting factorFs = 1e4; param = struct([]); param(1).Name ='截止频率(Hz)';Param(1).InitialValue = 0.48 * FS / 2;param(1).limits = fs / 2 * [1e-5,.9999];param(2).name ='RLS Forgetting Factor';Param(2).initialValue = 0.99;param(2).limits = [.3,1];hui = helpercreateparamtuningui(param,'RLS FIR Demo');套装(惠,'Position',[outerSize+32, screen(4)-2*outerSize+8,......outerSize+8, outerSize-92]);% Execute algorithm尽管(numTSteps>=0) S = HelperUnpackUIData(hUI); drawnowlimitrate;% needed to process UI callbacks[tfe,err] = myRLSFilterSystemIDSim(S);ifS.Stop% If "Stop Simulation" button is pressed休息;endifS.Pause.继续;end% Plot transfer functionsTFESCOPE(20 * log10(ABS(TFE)));% Plot learning curvemsescope(10*log10(sum(err.^2))); numTSteps = numTSteps - 1;endifishghandle(hUI)% If parameter tuning UI is open, then close it.delete(hUI); drawnow; clearhUIendscopeHandles.tfescope = tfescope; scopeHandles.msescope = msescope;end

Test the MATLAB Application

运行系统标识应用程序100时间步骤。应用程序运行仿真100次步骤或直到您单击停止模拟. It plots the results on scopes.

scope1 = myrlsfiltersystemidapp(100);释放(范围1.tfescope);发布(范围1.msescope);

Prepare Algorithm for Acceleration

当您使用MATLAB编码器加速MATLAB算法时,代码必须适合代码生成。

1. Make sure thatmyRLSFilterSystemIDSim.m包括%#codegen.函数签名后指令。

This directive indicates that you intend to generate code for the function. In the MATLAB Editor, it enables the code analyzer to detect code generation issues.

2. Screen the algorithm for unsupported functions or constructs.

coder.screener('myRLSFilterSystemIDSim');

The code generation readiness tool does not find code generation issues in this algorithm.

加速算法

要加速算法,此示例使用MATLAB编码器Codegen.command. Alternatively, you can use the MATLAB Coder app. For code generation, you must specify the type, size, and complexity of the input arguments. The functionmyRLSFilterSystemIDSim采用存储调整信息的结构。定义示例调整结构并将其传递给Codegen.by using the-argsoption.

ParamStruct.TuningValues = [2400 0.99]; ParamStruct.ValuesChanged = false; ParamStruct.Reset = false; ParamStruct.Pause = false; ParamStruct.Stop = false; codegenmyRLSFilterSystemIDSim-args{paramstruct};
代码成功。

Codegen.创建MEX功能myRLSFilterSystemIDSim_mexin the current folder.

Compare MEX Function and MATLAB Function Performance

1. Time 100 executions ofmyRLSFilterSystemIDSim.

clearmyRLSFilterSystemIDSimDISP('Running the MATLAB function ...')Tic.nTimeSteps = 100;forind = 1:nTimeSteps myRLSFilterSystemIDSim(ParamStruct);endtmatlab = toc;
Running the MATLAB function ...

2. Time 100 executions ofmyRLSFilterSystemIDSim_mex.

clearmyRLSFilterSystemIDSimDISP('Running the MEX function ...')Tic.forind = 1:nTimeSteps myRLSFilterSystemIDSim_mex(ParamStruct);endtmex = toc;DISP('结果:')disp(['Time for original MATLAB function: ', num2str(tMATLAB),......'秒']);DISP(['Time for MEX function: ', num2str(tMEX),'秒']);DISP(['mex函数是',num2str(tmatlab / tmex),......'比原来的matlab函数更快。']);
Running the MEX function ... RESULTS: Time for original MATLAB function: 2.0175 seconds Time for MEX function: 0.25939 seconds The MEX function is 7.7777 times faster than the original MATLAB function.

Optimize the MEX code

您有时可以使用不同的C / C ++编译器或使用某些选项或优化生成更快的MEX。看加速Matlab算法(MATLAB Coder).

对于此示例,MEX足够快而无需进一步优化。

修改应用程序调用MEX函数

调整myrlsfiltersystemidapp.so that it callsmyRLSFilterSystemIDSim_mexinstead ofmyRLSFilterSystemIDSim.

保存修改后的功能myrlsfiltersystemidapp_acc.m ...

Test the Application with the Accelerated Algorithm

clearmyRLSFilterSystemIDSim_mex;scope2 = myRLSFilterSystemIDApp_acc(100); release(scope2.tfescope); release(scope2.msescope);

The behavior of the application that calls the MEX function is the same as the behavior of the application that calls the original MATLAB function. However, the plots update more quickly because the simulation is faster.

Create the Standalone Application

1. To open the Application Compiler App, on the应用tab, underApplication Deployment,单击“应用”图标。

2. Specify that the main file ismyrlsfiltersystemidapp._acc.

The app determines the required files for this application. The app can find the MATLAB files and MEX-files that an application uses. You must add other types of files, such as MAT-files or images, as required files.

3. In thePackaging Optionssection of the toolstrip, make sure that the运行时从Web下载复选框是选中的。

此选项创建一个应用程序安装程序,该应用程序下载并使用已部署的MATLAB应用程序安装MATLAB运行时。

4.点击Package和save the project.

5. In the Package window, make sure that theOpen output folder when process completes复选框是选中的。

When the packaging is complete, the output folder opens.

安装应用程序

1. Open thefor_redistributionfolder.

2.运行myappinstaller_web..

3. If you connect to the internet by using a proxy server, enter the server settings.

4. Advance through the pages of the installation wizard.

  • On the Installation Options page, use the default installation folder.

  • On the Required Software page, use the default installation folder.

  • 在许可协议页面上,阅读许可协议并接受许可证。

  • 在确认页面上,单击安装.

If the MATLAB Runtime is not already installed, the installer installs it.

5. Click结束.

Run the Application

1.打开终端窗口。

2. Navigate to the folder where the application is installed.

  • For Windows®, navigate toC:\Program Files\myRLSFilterSystemIDApp_acc.

  • 对于麦克斯,导航到/ applications / myrlsfiltersystemidapp_acc.

  • 对于Linux,导航到/usr/myRLSFilterSystemIDApp_acc.

3. Run the application by using the appropriate command for your platform.

  • 适用于Windows,使用application \ myrlsfiltersystemidapp_acc..

  • For macOS, usemyrlsfiltersystemidapp._acc.app/Contents/MacOS/myRLSFilterSystemIDApp_acc.

  • For Linux, use/myRLSFilterSystemIDApp_acc.

Starting the application takes approximately the same amount of time as starting MATLAB.

相关话题

External Websites