Visual Servoing Platform  version 3.6.1 under development (2024-11-27)
tutorial-matlab.cpp
1 
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
10 #include <engine.h>
11 #include <matrix.h>
12 #include <visp3/core/vpConfig.h>
13 #include <visp3/core/vpMatrix.h>
15 
16 int main()
17 {
18 #ifdef ENABLE_VISP_NAMESPACE
19  using namespace VISP_NAMESPACE_NAME;
20 #endif
21 
22  // ViSP matrix containing input data
24  vpMatrix x(3, 3, 0);
25  x[0][0] = 1;
26  x[0][1] = 2;
27  x[0][2] = 3;
28  x[1][0] = 4;
29  x[1][1] = 5;
30  x[1][2] = 6;
31  x[2][0] = 7;
32  x[2][1] = 8;
33  x[2][2] = 9;
35  int xCols = x.getCols();
36  int xRows = x.getRows();
37 
39  // MATLAB Engine
40  Engine *ep;
41 
42  // MATLAB array to store input data to MATLAB
43  mxArray *T = mxCreateDoubleMatrix(xRows, xCols, mxREAL);
44 
45  // MATLAB array to store output data from MATLAB
46  mxArray *D = nullptr;
48 
49  // Temporary variable to hold Output data
50  double res[3];
51  int resCols = 3;
52 
53  // Display input data to the user
54  std::cout << "ViSP Input Matrix:" << std::endl;
55  for (size_t i = 0; i < xRows; i++) {
56  for (size_t j = 0; j < xCols; j++)
57  std::cout << x.data[i * xCols + j] << " ";
58  std::cout << std::endl;
59  }
60 
61  // Start a MATLAB Engine process using engOpen
63  if (!(ep = engOpen(""))) {
64  fprintf(stderr, "\nCan't start MATLAB engine\n");
65  return EXIT_FAILURE;
66  }
68 
69  // Copy the contents of ViSP matrix to the MATLAB matrix variable T
71  memcpy((void *)mxGetPr(T), (void *)x.data, xRows * xCols * sizeof(double));
73 
74  // Place the variable T into the MATLAB workspace
76  engPutVariable(ep, "Tm", T);
78 
79  // Determine the sum of each column of input matrix x
80  // ViSP matrix is row-major and MATLAB matrix is column-major, so transpose the matrix T before evaluation
82  engEvalString(ep, "Dm = sum(Tm');");
84 
85  // Get the variable D from the MATLAB workspace
87  D = engGetVariable(ep, "Dm");
89 
90  // Copy the contents of MATLAB variable D to local variable res
92  memcpy((void *)res, (void *)mxGetPr(D), sizeof(res));
94 
95  // Display output data to the user
96  std::cout << std::endl << "MATLAB Output Matrix (Column-wise sum):" << std::endl;
97  for (size_t i = 0; i < resCols; i++)
98  std::cout << res[i] << " ";
99  std::cout << std::endl;
100 
101  // Wait until user exits
102  std::cout << std::endl << "Hit return to quit\n" << std::endl;
103  fgetc(stdin);
104 
105  // Free memory, close MATLAB Engine and Exit
107  mxDestroyArray(T);
108  mxDestroyArray(D);
109  engEvalString(ep, "close;");
110  engClose(ep);
112 
113  return EXIT_SUCCESS;
114 }
Implementation of a matrix and operations on matrices.
Definition: vpMatrix.h:169