Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
CreateModelThatUsesMATLABFunctionBlockMATLAB&Simulink
CreateModelThatUsesMATLABFunctionBlock
Onthispage
AddingaMATLABFunctionBlocktoaModel
ProgrammingtheMATLABFunctionBlock
BuildingtheFunctionandCheckingforErrors
DefiningInputsandOutputs
AddingaMATLABFunctionBlocktoaModel
1. CreateanewmodelwiththeSimulink productandaddaMATLABFunctionblocktoitfromtheUser
DefinedFunctionlibrary:
2. AddthefollowingSourceandSinkblockstothemodel:
FromtheSourceslibrary,addaConstantblocktotheleftoftheMATLABFunctionblockandsetits
valuetothevector[2345].
FromtheSinkslibrary,addtwoDisplayblockstotherightoftheMATLABFunctionblock.
Themodelshouldnowhavethefollowingappearance:
3. IntheSimulinkEditor,selectFile>SaveAsandsavethemodelascall_stats_block1.
ProgrammingtheMATLABFunctionBlock
Thefollowingexerciseshowsyouhowtoprogramtheblocktocalculatethemeanandstandarddeviationfor
avectorofvalues:
1. Openthecall_stats_block1modelthatyousavedattheendofAddingaMATLABFunctionBlock
toaModel.DoubleclicktheMATLABFunctionblockfcntoopenitforediting.
Adefaultfunctionsignatureappears,alongwiththe%#codegendirective.Thedirectiveindicatesthatyou
intendtogeneratecodefromthisalgorithmandturnsonappropriateerrorchecking(seeCompilation
Directive%#codegen.
2. Editthefunctionheaderlineasfollows:
function[mean,stdev]=stats(vals)
%#codegen
http://www.mathworks.com/help/simulink/ug/creatinganexamplemodelthatusesamatlabfunctionblock.html
1/4
11/21/2014
CreateModelThatUsesMATLABFunctionBlockMATLAB&Simulink
Thefunctionstatscalculatesastatisticalmeanandstandarddeviationforthevaluesinthevector
vals.Thefunctionheaderdeclaresvalsasanargumenttothestatsfunction,withmeanandstdevas
returnvalues.
3. Savethemodelascall_stats_block2.
4. CompletetheconnectionstotheMATLABFunctionblockasshown.
5. IntheMATLABFunctionBlockEditor,enteralinespaceafterthefunctionheaderandaddthefollowing
code:
%calculatesastatisticalmeanandastandard
%deviationforthevaluesinvals.
len=length(vals);
mean=avg(vals,len);
stdev=sqrt(sum(((valsavg(vals,len)).^2))/len);
plot(vals,'+');
functionmean=avg(array,size)
mean=sum(array)/size;
Moreaboutlength
Moreaboutlen
Moreaboutplot
6. Savethemodelascall_stats_block2.
BuildingtheFunctionandCheckingforErrors
AfterprogrammingaMATLABFunctionblockinaSimulinkmodel,youcanbuildthefunctionandtestfor
errors.Thissectiondescribesthesteps:
1. Setupyourcompiler.
2. Buildthefunction.
3. Locateandfixerrors.
SettingUpYourCompiler
BuildingyourMATLABFunctionblockrequiresasupportedcompiler.MATLABautomaticallyselectsoneas
thedefaultcompiler.IfyouhavemultipleMATLABsupportedcompilersinstalledonyoursystem,youcan
changethedefaultusingthemexsetupcommand.SeeChangingDefaultCompiler.
SupportedCompilersforSimulationBuilds.Toviewalistofcompilersforbuildingmodelscontaining
MATLABFunctionblocksforsimulation:
http://www.mathworks.com/help/simulink/ug/creatinganexamplemodelthatusesamatlabfunctionblock.html
2/4
11/21/2014
CreateModelThatUsesMATLABFunctionBlockMATLAB&Simulink
1. NavigatetotheSupportedandCompatibleCompilers
(http://www.mathworks.com/support/compilers/current_release/)Webpage.
2. Selectyourplatform.
3. InthetableforSimulinkandrelatedproducts,findthecompilerscheckedinthecolumntitledSimulink
forMATLABFunctionblocks.
SupportedCompilersforCodeGeneration.TogeneratecodeformodelsthatcontainMATLABFunction
blocks,youcanuseanyoftheCcompilerssupportedbySimulinksoftwareforcodegenerationwith
SimulinkCoder.Foralistofthesecompilers:
1. NavigatetotheSupportedandCompatibleCompilers
(http://www.mathworks.com/support/compilers/current_release/)Webpage.
2. Selectyourplatform.
3. InthetableforSimulinkandrelatedproducts,findthecompilerscheckedinthecolumntitledSimulink
Coder.
HowtoGenerateCodefortheMATLABFunctionBlock
1. Openthecall_stats_block2modelthatyousavedattheendofProgrammingtheMATLAB
FunctionBlock.
2. DoubleclickitsMATLABFunctionblockstatstoopenitforediting.
3. IntheMATLABFunctionBlockEditor,selectBuildModel>Buildtocompileandbuildtheexample
model.
Ifnoerrorsoccur,theSimulationDiagnosticswindowdisplaysamessageindicatingsuccess.
Otherwise,thiswindowhelpsyoulocateerrors,asdescribedinHowtoLocateandFixErrors.
HowtoLocateandFixErrors
Iferrorsoccurduringthebuildprocess,theSimulationDiagnosticswindowliststheerrorswithlinkstothe
offendingcode.
ThefollowingexerciseshowshowtolocateandfixanerrorinaMATLABFunctionblock.
1. Inthestatsfunction,changethelocalfunctionavgtoafictitiouslocalfunctionaugandthencompile
againtoseethefollowingmessagesinwindow:
TheSimulationDiagnosticswindowdisplayseachdetectederrorwitharedbutton.
2. Clickthefirsterrorlinetodisplayitsdiagnosticmessageinthebottomerrorwindow.
Themessagealsolinkstoareportaboutcompiletimetypeinformationforvariablesandexpressionsin
yourMATLABfunctions.Thisinformationhelpsyoudiagnoseerrormessagesandunderstandtype
propagationrules.Formoreinformationaboutthereport,seeMATLABFunctionReports.
3. Inthediagnosticmessagefortheselectederror,clickthebluelinkafterthefunctionnametodisplaythe
offendingcode.
TheoffendinglineappearshighlightedintheMATLABFunctionBlockEditor:
4. Correcttheerrorbychangingaugbacktoavgandrecompile.
DefiningInputsandOutputs
InthestatsfunctionheaderfortheMATLABFunctionblockyoudefinedinProgrammingtheMATLAB
FunctionBlock,thefunctionargumentvalsisaninput,andmeanandstdevareoutputs.Bydefault,
functioninputsandoutputsinherittheirdatatypeandsizefromthesignalsattachedtotheirports.Inthis
topic,youexamineinputandoutputdatafortheMATLABFunctionblocktoverifythatitinheritsthecorrect
http://www.mathworks.com/help/simulink/ug/creatinganexamplemodelthatusesamatlabfunctionblock.html
3/4
11/21/2014
CreateModelThatUsesMATLABFunctionBlockMATLAB&Simulink
typeandsize.
1. Openthecall_stats_block2modelthatyousavedattheendofProgrammingtheMATLAB
FunctionBlock.DoubleclicktheMATLABFunctionblockstatstoopenitforediting.
2. IntheMATLABFunctionBlockEditor,selectEditData.
ThePortsandDataManageropenstohelpyoudefineargumentsforMATLABFunctionblocks.
Theleftpanedisplaystheargumentvalsandthereturnvaluesmeanandstdevthatyouhavealready
createdfortheMATLABFunctionblock.NoticethatvalsisassignedaScopeofInput,whichisshort
forInputfromSimulink.meanandstdevareassignedtheScopeofOutput,whichisshortforOutput
toSimulink.
3. IntheleftpaneofthePortsandDataManager,clickanywhereintherowforvalstohighlightit.
TherightpanedisplaystheDatapropertiesdialogboxforvals.Bydefault,theclass,size,and
complexityofinputandoutputargumentsareinheritedfromthesignalsattachedtoeachinputoroutput
port.InheritanceisspecifiedbysettingSizeto1,ComplexitytoInherited,andTypetoInherit:
SameasSimulink.
Theactualinheritedvaluesforsizeandtypearesetduringcompilationofthemodel,andarereportedin
theCompiledTypeandCompiledSizecolumnsoftheleftpane.
YoucanspecifythetypeofaninputoroutputargumentbyselectingatypeintheTypefieldoftheData
propertiesdialogbox,forexample,double.Youcanalsospecifythesizeofaninputoroutputargument
byenteringanexpressionintheSizefield.Forexample,youcanenter[23]intheSizefieldtospecify
valsasa2by3matrix.SeeTypeFunctionArgumentsandSizeFunctionArgumentsformore
informationontheexpressionsthatyoucanenterfortypeandsize.
Note:ThedefaultfirstindexforanyarraysthatyouaddtoaMATLABFunctionblockfunctionis
1,justasitwouldbeinMATLAB.
Formoreinformation,seePortsandDataManager.
http://www.mathworks.com/help/simulink/ug/creatinganexamplemodelthatusesamatlabfunctionblock.html
4/4