您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 国内外标准规范 > MatLab API in C
MatLabAPIinC++ChristopherDabneyPurposeMatLab…isaninterpretedscriptinglanguageconversiontoobjectcodeisatruntime;computationtimecanbealittleslowhasexcellentprototypingandplottingfunctionalitycontainsconvenientandveryrobustmatrixoperationpackagesPurpose(cont)C++isaprogramminglanguage,optimalandwithhighspeedfloatingpointcomputationisnon-trivialtoproducevisualeffectsineg.plotting,GUIs,nicetablescanbedifficulttosecurearobustvectoralgebrapackageforPurpose(cont)Solution:C++invokingMatLabcommandsnumbercrunchinginC++matrixoperationsinMatLabplotting,graphing,tablesinMatLabForprogrammerswitharobust&complexC++programintendingtoplotresultstheyarealreadyobtainingForMatLabprogrammingwithscriptswhichfrequentlylagInteractingwithMatLabNotrestrictedtoC++;Java,Perl,Fortran,andotherlanguagescandoitalsoNotrestrictedtotheMSVisualStudioenvironmentthedemosarewritteninAlsopossibletoinvokeaC++routinefromMatLab’senvironmentThreewaystointeractSendDatafromC++toMatLabCallaMatLabfunctionfromC++GenerateaDynamicLinkLibrary(dll)filefroma.mfileWewillusethefirstoneDemoRequirementsAC++CompilerthedemousesMSVisualC++v.6.0MatLabthedemousesMatLabv.7.0.1Assume’spriorprogrammingexperienceinbothMatLabandC++noexplanationsaregivenforthecommandsFollowingslidesexplainsettingupthedemonstrationprogramenvironmentSettinguptheEnvironmentCreatingpathstoMatLab:-Tools-Options-DirectoriesTab-SelectIncludefilesfromthedrop-downlist-AddC:\MATLAB701\EXTERN\INCLUDEtothelist-SelectLibraryFilesfromthedrop-downlist-Add”C:\MATLAB701\EXTERN\LIB\WIN32\MICROSOFT\MSVC60“LibrarypathsvarydependingonthelanguageandcompilerScreenshotSettinguptheEnvironment(cont)Twowaystoincludetheappropriatelibraryfiles:Method1)-Project-Settings-LinksTabUnderObject/LibraryModule:,addthreefilenames:-Libmx.lib-libmex.lib-libeng.libMethod2)Addthefollowinglinesofcodejustundertheincludesinthesourcecode:#pragmacomment(lib,Libmx.lib)#pragmacomment(lib,libmex.lib)#pragmacomment(lib,libeng.lib)ScreenshotConnectingtoMatLabEngineHeader:#includeengine.h,MatLab’sEngineIntheprogram,createapointertoit:Engine*m_pEngine;m_pEngine=engOpen(NULL);if(m_pEngine==NULL){coutError:NotFound”endl;exit(1);}InvokingCommandsengEvalString(Engine*ptr,stringcmd);engEvalString(m_pEngine,“x=1:1:10);“);engEvalString(m_pEngine,“y=x.^2;“);engEvalString(m_pEngine,“plot(x,y);“);EnablesprogrammertoinvokeanycommandinMatLabfromtheC++platform(convenient)Notspecialbyitself-mightaswellworkstraightfromMatLabIObetweenC++andMatLabUsethe“matrixarray”mxArraydatatypeEveryvariableinMatLabisamatrix–forC++toexchangedatawithit,adatatypethatbothC++andMatLabrecognizeisneededmxArraycan“bundle”C++variablesasmatrices,sobothplatformsrecognizethisdatatypeInsertingValues(input)Topassavariable,eg.x[0],intoMatLab,createanmxArrayforit-Allocatethespace(mxCreateDoubleMatrix)-Copythevalue(memcpy)-NamethevariableintheEngine(engPutVariable)doublex[0];mxArray*m_X;m_X=mxCreateDoubleMatrix(1,1,mxREAL);memcpy((void*)mxGetPr(m_X),(void*)x,sizeof(double)*1);engPutVariable(m_pEngine,x,m_X);Pointerm_pEngineisusedtospecifytheengineVariablexintheMatLabEnginegetsthevalueofx[0]inC++ExtractingValues(output)ToextracttheMatLabEngine’svariablez,pullitintoC++asamxArraymatrix,thenextractthebundledvalueoutofthatmxArrayandintoaC++variabledouble*cresult;mxArray*mresult;mresult=engGetVariable(m_pEngine,z);cresult=mxGetPr(mresult);coutcresult[0];mxGetPrreturnsapointertoacopyofthedoublevaluezstoredintheMatLabEngineWarning:UnpredictablefatalerrorsoccurifthedatatypeinMatLabdoesn’tcloselyresemblethedatatypeinC++eg.Copyinga3x1vectorintoascalarPassingArrays&MatricesTopassarrays(vector),adjustthesizeparametersofthememoryallocationandcopyroutinetomatchthedimensionsofthearraybeingpassedPassavectoraofdimensions:1xSIZEdoublea[SIZE];mxArray*A;//assumeagetsinitialized,allvaluesA=mxCreateDoubleMatrix(1,SIZE,mxREAL);memcpy((void*)mxGetPr(A),(void*)a,sizeof(double)*SIZE);engPutVariable(m_pEngine,a,A);CopiesentireC++arrayaintotheMatLabEngine’saPassingArrays&Matrices(cont)Passamatrixofdimensions:SIZExSIZEdoublec[SIZE][SIZE];//assumecgetsinitialized,allofitmxArray*mxc;mxc=mxCreateDoubleMatrix(SIZE,SIZE,mxREAL);memcpy((void*)mxGetPr(mxc),(void*)c,sizeof(double)*SIZE*SIZE);engPutVariable(m_pEngine,c,mxc);engEvalString(m_pEngine,c=c';);Note:C++hasrow-majorstorage,andMatLabhascolumn-majorstorage.Thusamatrixbeingexchangedmustbetransposed,eitherbeforeoraftertheexchange,tomaintainthematrix’ssemanticsSeetheDemosProgramDemonstratesallofthesefeaturessofarinMicrosoftVisualDevelopmentStudioC++v.6.0Demonstratesgraphplots,invokingcommands,input,output,andpassingvectorsandmatrices.InternetReferencesWelcometoZhenwang'sHomepage(Q&A)~zyao/teaching/ensc488faq.htmATutorialtoCallMATLABFunctionsfromWithinAC/C++ProgramMicrosoftVisualStudioC++&InterfacingMatlabwithC/C++,JavaMatLab–TheLanguageofTechnicalCo
本文标题:MatLab API in C
链接地址:https://www.777doc.com/doc-3383617 .html