void LatexInsert3DPlot(klMatrix<double>& mat, ofstream &_tex, string dir,string filename,string title,klHoldOnStatus holdon,const char* markerType) { klMatlabEngineThreadMap klmtm; Engine* matlabEngine=klmtm.find(klThread<klMutex>::getCurrentThreadId() ); char* arg = new char[2048]; char* evalString = new char[2048]; sprintf(arg,"%s//%s.eps",dir.c_str(),filename.c_str()); const char* xAxis=NULL; const char* yAxis=NULL; const char* zAxis=NULL; bool useExtents=true; klScatterPlot3D(mat,filename.c_str(),title.c_str(), xAxis, yAxis,zAxis, useExtents, holdon, markerType); if(holdon==klHoldOnStatus::LastPlot || holdon==klHoldOnStatus::NoHold ) { sprintf(evalString,"print -r1200 -depsc %s;",arg); engEvalString(matlabEngine, evalString); engEvalString(matlabEngine, "hold off;close(gcf);"); sprintf(evalString,"epstopdf %s",arg); system(evalString); sprintf(arg,"%s.pdf",filename.c_str()); _tex<<"\\includegraphics[width=10.0cm,height=10.0cm]{"<<arg<<"}"<<endl<<endl; } delete arg; delete evalString; }
int main(int argc, const char *argv[]) { Engine *ep; char buff[10240]; int i; /* matlab must be in the PATH! */ if (!(ep = engOpen("matlab -nodisplay"))) { fprintf(stderr, "Can't start MATLAB engine\n"); return -1; } engOutputBuffer(ep, buff, 10239); /* load the mex file */ if(argc<2){ fprintf(stderr, "Error. Give full path to the MEX file as input parameter.\n"); return -1; } void *handle = dlopen(argv[1], RTLD_NOW); if(!handle){ fprintf(stderr, "Error loading MEX file: %s\n", strerror(errno)); return -1; } /* grab mexFunction handle */ mexFunction_t mexfunction = (mexFunction_t)dlsym(handle, "mexFunction"); if(!mexfunction){ fprintf(stderr, "MEX file does not contain mexFunction\n"); return -1; } /* load input data - for convenience do that using MATLAB engine */ /* NOTE: parameters are MEX-file specific, so one has to modify this*/ /* to fit particular needs */ engEvalString(ep, "load input.mat"); mxArray *arg1 = engGetVariable(ep, "im1"); mxArray *arg2 = engGetVariable(ep, "im2"); mxArray *arg3 = engGetVariable(ep, "szx"); mxArray *arg4 = engGetVariable(ep, "szy"); mxArray *arg5 = engGetVariable(ep, "ngh"); mxArray *pargout[1] = {0}; const mxArray *pargin[5] = {arg1, arg2,arg3, arg4,arg5}; /* execute the mex function */ mexfunction(1, pargout, 5, pargin); /* print the results using MATLAB engine */ engPutVariable(ep, "result", pargout[0]); engEvalString(ep, "result"); printf("%s\n", buff); /* cleanup */ mxDestroyArray(pargout[0]); engEvalString(ep, "clear all;"); dlclose(handle); engClose(ep); return 0; }
void LatexInsertHistogram(klVector<double>& vec, unsigned int numBins,ofstream &_tex, string dir,string filename,string title) { /*vec.setupRange(); klVector<double> hist=vec.histogram(numBins,vec.y0,vec.y1); hist.setupRange(); hist.setupDomain(vec.y0,vec.y1);*/ klMatlabEngineThreadMap klmtm; Engine* matlabEngine=klmtm.find(klThread<klMutex>::getCurrentThreadId() ); char* arg = new char[2048]; char* evalString = new char[2048]; sprintf(arg,"%s\\%s.eps",dir.c_str(),filename.c_str()); //klPlot1D<double>(hist,arg,title.c_str()); klPlotHistogram<double>(vec,arg,title.c_str()); sprintf(evalString,"print -r1200 -depsc %s;",arg); engEvalString(matlabEngine, evalString); engEvalString(matlabEngine, "hold off;close(gcf);"); sprintf(evalString,"epstopdf %s",arg); system(evalString); sprintf(arg,"%s.pdf",filename.c_str()); _tex<<"\\includegraphics[width=10.0cm,height=10.0cm]{"<<arg<<"}"<<endl<<endl; delete arg; delete evalString; }
bool Eval(Engine *ep, char *out, const char *cmd, ...) { char buf[BUFSIZE]; va_list args; va_start(args, cmd); vsprintf(buf, cmd, args); va_end(args); engEvalString(ep, "clear engerr; lasterr('');"); engEvalString(ep, buf); printf("%s", out); engEvalString(ep, "engerr = lasterr;"); mxArray *err = engGetVariable(ep, "engerr"); if (err == NULL) { printf("unable to retrieve variable 'engerr'\n\n"); return false; } bool ok = (mxGetNumberOfElements(err) == 0); mxDestroyArray(err); return ok; }
int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow){ char buffer[BUFSIZE]; mxArray *app; Engine *ep; /* 啟動 MATLAB 引擎 */ if (!(ep = engOpen(NULL))){ // 產生一個 MATLAB 引擎物件 MessageBox ((HWND)NULL, (LPSTR)"Can't start MATLAB engine", (LPSTR)"plotViaMatlab01.c", MB_OK); exit(-1); } /* 切換目錄並執行 plotSine.m */ _getcwd(buffer, BUFSIZE); // 將此程式所在目錄存入字串 buffer app = mxCreateString(buffer); // 產生 MATLAB 內部的字串變數 app engPutVariable(ep, "appDir", app); // 將字串變數 app 至入工作空間的變數 appDir engEvalString(ep, "cd(appDir)"); // 將 MATLAB 的工作目錄切換至字串 appDir 所指定的目錄 engEvalString(ep, "plotSine"); // 執行同目錄下的 plotSine.m /* 取得 MATLAB 輸出訊息 */ engOutputBuffer(ep, buffer, BUFSIZE); // 設定 buffer 可以接收 MATLAB 的輸出訊息 engEvalString(ep, "whos"); // 在 MATLAB 引擎執行 whos 指令 MessageBox((HWND)NULL, (LPSTR)buffer, (LPSTR) "MATLAB - whos", MB_OK); // 顯示 buffer 的內容 engClose(ep); // 最後關閉 MATLAB 引擎 return(0); }
void MatlabAdapter::initModel() { mEngine = engOpen(mEngineArgs.size() ? mEngineArgs.toStdString().c_str(): "\0"); engOutputBuffer(mEngine, mBuffer, mBufferSize); if(mEngine == 0) { TRACE("warning: connection failed!"); } const QString modelDir = "cd '" + mWorkingDir + "/Projects/MMM" + "'"; TRACE("working dir is: %s", modelDir.toStdString().c_str()); int retVal = 0; retVal += engEvalString(mEngine, modelDir.toStdString().c_str()); retVal += engEvalString(mEngine, "initializeModelAdapter"); // *************** read out dofs **************************** retVal += engEvalString(mEngine, "numDOFs = length(Model.q0);"); mxArray* mxNumDOFs = 0; if((mxNumDOFs =engGetVariable(mEngine, "numDOFs")) == 0) { TRACE("WARNING: can't evaluate degrees of freedom"); mxDestroyArray(mxNumDOFs); return; } tree.dofs.resize(static_cast<int>(mxGetPr(mxNumDOFs)[0])); TRACE("model has %lu degrees of freedom", tree.dofs.size()); // ************** read out segment / joint information ************* retVal += engEvalString(mEngine, "numSegs = size(Model.Body,2);"); retVal += engEvalString(mEngine, "numJoints = size(Model.Joint,2);"); mxArray *mxNumSegs = 0, *mxNumJoints = 0; if((mxNumSegs =engGetVariable(mEngine, "numSegs")) == 0) { TRACE("WARNING: can't evaluate number of segments"); mxDestroyArray(mxNumSegs); return; } if((mxNumJoints =engGetVariable(mEngine, "numJoints")) == 0) { TRACE("WARNING: can't evaluate number of joints"); mxDestroyArray(mxNumJoints); return; } tree.jointNodes.resize(static_cast<int>(mxGetPr(mxNumJoints)[0])); tree.partNodes.resize(static_cast<int>(mxGetPr(mxNumSegs)[0])); //model.numJoints = static_cast<int>(mxGetPr(mxNumJoints)[0]); //model.numSegments = static_cast<int>(mxGetPr(mxNumSegs)[0]); mxDestroyArray(mxNumDOFs); mxDestroyArray(mxNumJoints); mxDestroyArray(mxNumSegs); }
WaveData SignalProcessTools::waveRead(string filename) { engEvalString(ep, ("[R,Fs]=audioread('"+filename+"');").c_str()); engEvalString(ep, "R=R(:,1);"); WaveData data; getVector(data.wave, "R"); mxArray *Fs = engGetVariable(ep, "Fs"); data.sampleRate = (int)mxGetPr(Fs)[0]; return data; }
void SignalProcessTools::plot(vector dataX, vector dataY, \ string title, string xLabel, string yLabel) { putVector(dataX, "X"); putVector(dataY, "Y"); engEvalString(ep, "plot(X,Y);"); if (title != "") engEvalString(ep, ("title('"+title+"');").c_str()); if (xLabel != "") engEvalString(ep, ("xlabel('"+xLabel+"');").c_str()); if (yLabel != "") engEvalString(ep, ("ylabel('"+yLabel+"');").c_str()); }
void SignalProcessTools::plotSpec(FreqData data) { int n1 = data.freq.length; int n2 = data.time.length; put2DData(data.real.data, n1, n2, "BReal"); put2DData(data.imag.data, n1, n2, "BImag"); string cmd = "B=BReal+i*BImag;imagesc(time,freq,abs(B));"; engEvalString(ep, cmd.c_str()); cmd = "axis('xy');xlabel('ʱ¼ä (Ãë)'); ylabel('ƵÂÊ (Hz)');"; engEvalString(ep, cmd.c_str()); }
PyObject * mlabraw_eval(PyObject *, PyObject *args) { //XXX how large should this be? const int BUFSIZE=10000; char* fmt = "try, %s; MLABRAW_ERROR_=0; catch, MLABRAW_ERROR_=1; end;"; char buffer[BUFSIZE]; char cmd[BUFSIZE]; char *lStr; char *retStr = buffer; PyObject *ret; PyObject *lHandle; if (! PyArg_ParseTuple(args, "Os:eval", &lHandle, &lStr)) return NULL; if (! PyCObject_Check(lHandle)) { PyErr_SetString(PyExc_TypeError, "Invalid object passed as mlabraw session handle"); return NULL; } sprintf(cmd, fmt, lStr); //FIXME check buffer overflow // std::cout << "DEBUG: CMD " << cmd << std::endl << std::flush; engOutputBuffer((Engine *)PyCObject_AsVoidPtr(lHandle), retStr, BUFSIZE-1); if (engEvalString((Engine *)PyCObject_AsVoidPtr(lHandle), cmd) != 0) { PyErr_SetString(mlabraw_error, "Unable to evaluate string in MATLAB(TM) workspace"); return NULL; } { mxArray *lArray = NULL; char buffer2[BUFSIZE]; char *retStr2 = buffer2; bool __mlabraw_error; if (NULL == (lArray = _getMatlabVar(lHandle, "MLABRAW_ERROR_")) ) { PyErr_SetString(mlabraw_error, "Something VERY BAD happened whilst trying to evaluate string " "in MATLAB(TM) workspace."); return NULL; } __mlabraw_error = (bool)*mxGetPr(lArray); mxDestroyArray(lArray); if (__mlabraw_error) { engOutputBuffer((Engine *)PyCObject_AsVoidPtr(lHandle), retStr2, BUFSIZE-1); if (engEvalString((Engine *)PyCObject_AsVoidPtr(lHandle), "disp(subsref(lasterror(),struct('type','.','subs','message')))") != 0) { PyErr_SetString(mlabraw_error, "THIS SHOULD NOT HAVE HAPPENED!!!"); return NULL; } PyErr_SetString(mlabraw_error, retStr2 + ((strncmp(">> ", retStr2, 3) == 0) ? 3 : 0)); return NULL; } } if (strncmp(">> ", retStr, 3) == 0) { retStr += 3; } //FIXME ret = (PyObject *)PyString_FromString(retStr); return ret; }
void MatlabAdapter::initGenCoords() { engEvalString(mEngine, "coordNames = {Model.GenCoor.Name}"); engEvalString(mEngine, "coordRanges = [ Model.lb; Model.ub]"); mxArray *mxNames = engGetVariable(mEngine, "coordNames"); mxArray *mxRanges = engGetVariable(mEngine, "coordRanges"); double* values = mxGetPr(mxRanges); double min, max, stepSize; unsigned size = tree.dofs.size(); for(unsigned i=0; i < size; i++) { mxArray *mxCell = mxGetCell(mxNames, i); char* name = mxArrayToString(mxCell); min = values[i]; max = values[i+size]; stepSize = (max-min) / 100.0; if(stepSize > 0.05) stepSize = 0.05; DegreeOfFreedom dof(min, max, 0, stepSize); dof.name = name; if(dof.name.size() > 6) { if(dof.name.substr(0,6).compare("root_r") == 0) { TRACE("limited"); dof.rangeType = DegreeOfFreedom::limitedRange; dof.min = -5; dof.max = 5; } else { TRACE("circular"); dof.rangeType = DegreeOfFreedom::circularRange; dof.min = - M_PI; dof.max = + M_PI; } } tree.dofs.at(i)=dof; TRACE("generalized coordinat %s @ %i : min %f to %f", name, i, min, max); } mxDestroyArray(mxNames); mxDestroyArray(mxRanges); }
MATLABPLOTTER::MATLABPLOTTER() { //stuff // Start the MATLAB engine if (!(ep = engOpen(NULL))) { MessageBox ((HWND)NULL, (LPSTR)"Can't start MATLAB engine", (LPSTR) "Matlab.cpp", MB_OK); exit(-1); } engEvalString(ep, "iter=1;"); engEvalString(ep, "color_codes=['r' 'g' 'b' 'k' 'y'];"); }
void MATLABPLOTTER::plotfreqscan(std::vector <double> &FREQ_vector, std::vector <double> &DAQ_vector) { mxArray *data_freq = NULL; mxArray *data_DAQ = NULL; //Scan laser double *freq_data_ptr = (double*) calloc(FREQ_vector.size(), sizeof(double)); if (freq_data_ptr==NULL) exit(1); double *DAQ_data_ptr = (double*) calloc(DAQ_vector.size(), sizeof(double)); if (DAQ_data_ptr==NULL) exit(1); for(unsigned int i=0;i < DAQ_vector.size(); i++) { double stra = FREQ_vector.at(i); double strb = DAQ_vector.at(i); freq_data_ptr[i] = stra; DAQ_data_ptr[i] = strb; } data_freq = mxCreateDoubleMatrix(1, FREQ_vector.size(), mxREAL); memcpy((char*) mxGetPr(data_freq), freq_data_ptr, FREQ_vector.size()*sizeof(double)); data_DAQ = mxCreateDoubleMatrix(1, FREQ_vector.size(), mxREAL); memcpy((char*) mxGetPr(data_DAQ), DAQ_data_ptr, FREQ_vector.size()*sizeof(double)); /* * Place the variable dataFreq & dataDAQ into the MATLAB workspace */ engPutVariable(ep, "dataFreq", data_freq); engPutVariable(ep, "dataDAQ", data_DAQ); /* Plot the result */ //engEvalString(ep, "hold on;"); engEvalString(ep, "figure(1);"); engEvalString(ep, "plot(dataFreq(:)',dataDAQ(:)');"); engEvalString(ep, "title('Rb Scan');"); engEvalString(ep, "xlabel('Frequency (GHz)');"); engEvalString(ep, "ylabel('Absorbtion (V)');"); free(DAQ_data_ptr); free(freq_data_ptr); }
void MATLABPLOTTER::plotlockpoints(std::vector <double> &FITFREQ_vector, std::vector <double> &FITDAQ_vector) { mxArray *fit_data_freq = NULL; mxArray *fit_data_DAQ = NULL; //Scan laser double *fit_freq_data_ptr = (double*) calloc(FITFREQ_vector.size(), sizeof(double)); if (fit_freq_data_ptr==NULL) exit(1); double *fit_DAQ_data_ptr = (double*) calloc(FITDAQ_vector.size(), sizeof(double)); if (fit_DAQ_data_ptr==NULL) exit(1); for(unsigned int i=0;i < FITDAQ_vector.size(); i++) { double stra = FITFREQ_vector.at(i); double strb = FITDAQ_vector.at(i); fit_freq_data_ptr[i] = stra; fit_DAQ_data_ptr[i] = strb; } fit_data_freq = mxCreateDoubleMatrix(1, FITFREQ_vector.size(), mxREAL); memcpy((char*) mxGetPr(fit_data_freq), fit_freq_data_ptr, FITFREQ_vector.size()*sizeof(double)); fit_data_DAQ = mxCreateDoubleMatrix(1, FITFREQ_vector.size(), mxREAL); memcpy((char*) mxGetPr(fit_data_DAQ), fit_DAQ_data_ptr, FITFREQ_vector.size()*sizeof(double)); /* * Place the variable dataFreq & dataDAQ into the MATLAB workspace */ engPutVariable(ep, "fitdataFreq", fit_data_freq); engPutVariable(ep, "fitdataDAQ", fit_data_DAQ); /* Plot the result */ engEvalString(ep, "i=1"); for(unsigned int j=1; j <= FITFREQ_vector.size(); j++) { engEvalString(ep, "hold on;"); engEvalString(ep, "plot(fitdataFreq(i)',fitdataDAQ(i)', 's','MarkerSize',10, 'MarkerFaceColor','g','MarkerEdgeColor', 'r');"); engEvalString(ep, "i=i+1;"); } free(fit_DAQ_data_ptr); free(fit_freq_data_ptr); }
void Uav::initializeMatlabEngine() { matlabEngine = engOpen(NULL); if( !matlabEngine ) { qCritical("%s : Cannot open the MATLAB engine.", objectName().toStdString().c_str() ); }; // prepare an empty matrix to hold the ownship's track engEvalString(matlabEngine, "ownshipTrack = [];"); // prepare a plot figure to show that track engEvalString(matlabEngine, "figure('Name','UAV Track');"); engEvalString(matlabEngine, "axis equal;"); }
void MatLabEngine::executeCommand( const std::string &command, const bool unchecked ) { if ( _matLabLogFileStreamPtr ) { std::cerr << command << std::endl; (*_matLabLogFileStreamPtr) << "try\n\t" << command << "\nend" << std::endl; } if ( engEvalString( _ep, command.c_str() ) != 0 ) { _ep = 0; throw MatLabUdm::Exception( "MatLab connection lost." ); } _matLabOutput = getBuffer(); if ( _matLabOutput.find( "???" ) == 0 ) { #ifdef _DEBUG // KMS: is there a better way to check for an error??? std::string error = "Executing MatLab command '"; error += command + "' resulted in error '" + _matLabOutput; if (!unchecked) { #ifdef _WIN32 OutputDebugString(error.c_str()); DebugBreak(); #endif throw MatLabUdm::Exception(error); } else { #ifdef _WIN32 OutputDebugString(error.c_str()); #endif } #endif } }
int MatlabEvaluator::runAnalysis(const Vector &x) { // Let's just make a direct call since we have the pointer to OpenSees domain // This replaces above call to Tcl command; however, in the reset command // revertToStart() is also called on theTransientIntegrator -- MHS needs to check if (theOpenSeesDomain->revertToStart() != 0) { opserr << "ERROR MatlabEvaluator -- error in resetting Domain" << endln; return -1; } // Put random variables into the structural domain according to the RandomVariablePositioners int rvIndex; RandomVariablePositionerIter rvPosIter = theReliabilityDomain->getRandomVariablePositioners(); RandomVariablePositioner *theRVPos; while ((theRVPos = rvPosIter()) != 0) { rvIndex = theRVPos->getRvIndex(); theRVPos->update(x(rvIndex)); } // Start a Matlab engine Engine *ep; ep = engOpen("\0"); // Execute a Matlab function called 'matlabgfun' char theMatlabCommand[50]; sprintf(theMatlabCommand,"matlabgfun"); engEvalString(ep, theMatlabCommand); // Shut down the Matlab engine engClose(ep); return 0; }
void engcmd(const char* command) { char buffer[BUFSIZE]; //MatLab output buffer bool SUCCESS = true; //success flag if (NULL == Eng) //if not opened yet { msg("eng::noMLB"); //message SUCCESS = false; } else { engOutputBuffer(Eng, buffer, BUFSIZE); //for return output //issue command if(engEvalString(Eng, command)) //if unsucessful { msg("engCmd::erexe"); SUCCESS = false; } } if(SUCCESS) MLPutByteString(stdlink, buffer, strlen(buffer)); else MLPutSymbol(stdlink, "$Failed"); }
void MatLabEngine::executeInteractiveCommands( void ) { std::string command; while( true ) { char *commandString = readline( ">> " ); if ( !commandString ) { continue; } if ( *commandString ) { add_history( commandString ); } command = commandString; free( commandString ); if ( command.substr( 0, 4 ) == "quit" ) { break; } zeroBuffer(); if ( engEvalString( _ep, command.c_str() ) != 0 ) { _ep = 0; throw MatLabUdm::Exception( "MatLab connection lost." ); } std::string output( getBuffer() ); output = output.substr( output.find( '\n' ) + 1 ); std::cout << output << std::endl; } }
FreqData SignalProcessTools::stft(WaveData data, string windowName /* = "hamming" */, int windowN /* = 256 */, int NOverlap /* = 192 */, int NFFT /* = 256 */) { putWaveData(data); string cmd = "h=window('"+windowName+"',"+intToString(windowN)+")"; engEvalString(ep, cmd.c_str()); cmd = "[B,freq,time]=spectrogram(W,h,"+intToString(NOverlap)+","+intToString(NFFT)+",Fs);"; engEvalString(ep, cmd.c_str()); cmd = "BReal=real(B);BImag=imag(B);"; engEvalString(ep, cmd.c_str()); FreqData freq; getVector(freq.freq, "freq"); getVector(freq.time, "time"); getVector(freq.real, "BReal"); getVector(freq.imag, "BImag"); return freq; }
void MATLABPLOTTER::plotData(std::vector <double> &timeVector, std::vector <double> &signalVector, bool new_figure) { mxArray *data_time = NULL; mxArray *data_Signal = NULL; //Scan laser double *time_data_ptr = (double*) calloc(timeVector.size(), sizeof(double)); if (time_data_ptr==NULL) exit(1); double *Signal_data_ptr = (double*) calloc(signalVector.size(), sizeof(double)); if (Signal_data_ptr==NULL) exit(1); for(unsigned int i=0;i < signalVector.size(); i++) { double stra = timeVector.at(i); double strb = signalVector.at(i); time_data_ptr[i] = stra; Signal_data_ptr[i] = strb; } data_time = mxCreateDoubleMatrix(1, timeVector.size(), mxREAL); memcpy((char*) mxGetPr(data_time), time_data_ptr, timeVector.size()*sizeof(double)); data_Signal = mxCreateDoubleMatrix(1, timeVector.size(), mxREAL); memcpy((char*) mxGetPr(data_Signal), Signal_data_ptr, timeVector.size()*sizeof(double)); // Place the variable dataTime & dataSignal into the MATLAB workspace engPutVariable(ep, "dataTime", data_time); engPutVariable(ep, "dataSignal", data_Signal); // Plot the result if (new_figure) { engEvalString(ep, "close;"); engEvalString(ep, "figure;"); } else { engEvalString(ep, "hold on;"); } engEvalString(ep, "plot(dataTime(:)',dataSignal(:)', color_codes(round(rand*4+1)) );"); engEvalString(ep, "title('Scope Trace');"); engEvalString(ep, "xlabel('Time (s)');"); engEvalString(ep, "ylabel('Volts');"); engEvalString(ep, "iter=iter+1;"); free(Signal_data_ptr); free(time_data_ptr); }
void LatexInsertLegend(string legend) { klMatlabEngineThreadMap klmtm; Engine* matlabEngine=klmtm.find(klThread<klMutex>::getCurrentThreadId() ); stringstream evalString; evalString<<"legend("<<legend<<");"; engEvalString(matlabEngine, evalString.str().c_str()); }
void MATLABPLOTTER::saveVector(std::string filename) { std::string path = "\\\\epsrv1\\EP\\data\\ThermocoupleAutoSave\\"; std::string save_command = "dlmwrite('" + path + filename + "', inputData, '-append');"; engEvalString(ep, save_command.c_str()); }
void Uav::useMatlabEngine() { Q_ASSERT(matlabEngine); /* * Create a variable for our data */ mxArray* pos2d = mxCreateDoubleMatrix(1, 2, mxREAL); //NOTE: the UAV's (x,y,z) coordinates are given wrt. to the // North/x-East/y-Down/y frame of reference. // Matlab's plot function assume the standart mathematical // X/East-Y/North-Z/Up frame of reference... memcpy(static_cast<void*>(mxGetPr(pos2d)), static_cast<const void*>( &(ownship().position2D().y()) ), sizeof(ownship().position2D().x())) ; memcpy(static_cast<void*>(mxGetPr(pos2d)+1 ), static_cast<const void*>( &(ownship().position2D().x()) ), sizeof(ownship().position2D().y())) ; /* * Place the variable "pos2d" into the MATLAB workspace */ engPutVariable(matlabEngine, "pos2d", pos2d); // append the current position to the track engEvalString(matlabEngine, "ownshipTrack = [ownshipTrack; pos2d];"); /* * Plot the result */ engEvalString(matlabEngine, "plot(ownshipTrack(:,1),ownshipTrack(:,2),'-b',pos2d(1),pos2d(2),'+r');"); /* * Clean up */ mxDestroyArray(pos2d); }
void LatexInsertHeatMap(klMatrix<double>& mat, ofstream &_tex, string dir,string filename,string title) { klMatlabEngineThreadMap klmtm; Engine* matlabEngine=klmtm.find(klThread<klMutex>::getCurrentThreadId() ); char* arg = new char[2048]; char* evalString = new char[2048]; sprintf(arg,"%s//%s.eps",dir.c_str(),filename.c_str()); //klMatrix<TYPE> c,const char* filename, const char* title=NULL,const char* xAxis=NULL,const char* yAxis=NULL,const char* zAxis=NULL,bool useExtents=true,bool holdOn=false,const char* marker=NULL klHeatMapPlot<double>(mat,arg,title.c_str()); sprintf(evalString,"print -r1200 -depsc %s;",arg); engEvalString(matlabEngine, evalString); engEvalString(matlabEngine, "hold off;close(gcf);"); sprintf(evalString,"epstopdf %s",arg); system(evalString); sprintf(arg,"%s.pdf",filename.c_str()); _tex<<"\\includegraphics[width=10.0cm,height=10.0cm]{"<<arg<<"}"<<endl<<endl; delete arg; delete evalString; }
void Search_Synonym_LSI() //这里主要是把相关度前二十的诗词打包成向量投射到词汇空间 { double rvpoems[POEMSNUM]; memset(rvpoems , 0 , sizeof(rvpoems)); for (int i = 0 ; i <= 19 ; ++i) { rvpoems[ vresult[i] -1] = 1; } mxArray * vpoems_m = mxCreateDoubleMatrix(1,POEMSNUM, mxREAL); memcpy(mxGetPr(vpoems_m), rvpoems, POEMSNUM * sizeof(double)); engPutVariable(ep, "R",vpoems_m); engEvalString(ep, "BS=zeros(7474,1);"); engEvalString(ep, "AS = R*(V)*(inv(U));"); engEvalString(ep, "k = 1;"); for (int i=1 ;i<= WORDNUM ; ++i) { engEvalString(ep, "BS(k,1) = dot(AS,S(k,:)) / (norm(AS)*norm(S(k,:)) );"); engEvalString(ep, "k = k + 1;"); } engEvalString(ep, "[LS,INDS]=sort(BS,'descend');" ); mxArray * vsyn_m = engGetVariable(ep, "INDS" ); mxArray * srelation_m = engGetVariable(ep , "LS"); memcpy(rvsyn, mxGetPr(vsyn_m) , WORDNUM * sizeof(double)); memcpy(srelation , mxGetPr(srelation_m) , WORDNUM * sizeof(double)); mxDestroyArray(vpoems_m); mxDestroyArray(vsyn_m); }
int object_to_string(void *addr, char *value, int size) { mxArray **my = (mxArray**)addr; if (*my!=NULL) { engPutVariable(engine,"object",*my); engEvalString(engine,"disp(char(object));"); output[strlen(output)-1]='\0'; // trim CR off end return _snprintf(value,size-1,"[[%s]]",output); } else return 0; }
static mxArray* matlab_exec(MATLABLINK *matlab, char *format, ...) { char cmd[4096]; va_list ptr; va_start(ptr,format); vsprintf(cmd,format,ptr); va_end(ptr); engEvalString(matlab->engine,cmd); if ( matlab->output_buffer && strcmp(matlab->output_buffer,"")!=0 ) gl_verbose( "%s", matlab->output_buffer ); mxArray *ans = engGetVariable(matlab->engine,"ans"); return ans; // failed }
/* Record data for MATLAB processing. */ void recordData() { if (dataCounter<numberOfSamples) { dataSetVisual[dataCounter] = shift+((sizeOrig*size)/2); print_time(); } else if (dataCounter == numberOfSamples) { engPutVariable(ep, "cppVisualSamples", cppVisualSamples); engPutVariable(ep, "cppTimingSamples", cppTimingSamples); engEvalString(ep, "save visualdata.mat"); fprintf(stderr, "Recording of %i samples is complete. Data saved as \"visualdata.mat\".\n", numberOfSamples); recordMode = 0; dataCounter++; } }
int main(){ Engine *ep; mxArray *mX = NULL, *mY = NULL; const size_t N = 1024; if (!(ep = engOpen(NULL))) { fprintf(stderr, "\nCan't start MATLAB engine\n"); return EXIT_FAILURE; } mX = mxCreateDoubleMatrix(1, N, mxREAL); mY = mxCreateDoubleMatrix(1, N, mxREAL); double *x = (double *)mxGetPr(mX); double *y = (double *)mxGetPr(mY); for (size_t i=0; i<N; ++i){ x[i] = 2.0*M_PI*i/N; y[i] = sin(x[i]); } engPutVariable(ep, "x", mX); engPutVariable(ep, "y", mY); engEvalString(ep, "h = figure;"); engEvalString(ep, "plot(x, y); hold on;"); engEvalString(ep, "plot([0 0],ylim,'k'); plot(xlim,[0 0],'k');"); engEvalString(ep, "title('y = sin(x)');"); engEvalString(ep, "xlabel('x');"); engEvalString(ep, "ylabel('y');"); engEvalString(ep, "grid on; grid minor; box off;"); engEvalString(ep, "print(h,'-dpng','sin.png');"); engEvalString(ep, "close all;"); mxDestroyArray(mX); mxDestroyArray(mY); printf("Ok. Press ENTER to exit\n"); getchar(); engClose(ep); return EXIT_SUCCESS; }