Visual Servoing Platform  version 3.5.1 under development (2022-07-06)
tutorial-matlab.cpp
1
2 /*
3  * Tutorial using ViSP and MATLAB
4  * Determine column-wise sum of ViSP matrix using MATLAB Engine
5  */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
10 #include <engine.h>
11 #include <matrix.h>
12 #include <visp3/core/vpMatrix.h>
14
15 int main()
16 {
17  // ViSP matrix containing input data
19  vpMatrix x(3, 3, 0);
20  x[0][0] = 1;
21  x[0][1] = 2;
22  x[0][2] = 3;
23  x[1][0] = 4;
24  x[1][1] = 5;
25  x[1][2] = 6;
26  x[2][0] = 7;
27  x[2][1] = 8;
28  x[2][2] = 9;
30  int xCols = x.getCols();
31  int xRows = x.getRows();
32
34  // MATLAB Engine
35  Engine *ep;
36
37  // MATLAB array to store input data to MATLAB
38  mxArray *T = mxCreateDoubleMatrix(xRows, xCols, mxREAL);
39
40  // MATLAB array to store output data from MATLAB
41  mxArray *D = NULL;
43
44  // Temporary variable to hold Output data
45  double res[3];
46  int resCols = 3;
47
48  // Display input data to the user
49  std::cout << "ViSP Input Matrix:" << std::endl;
50  for (size_t i = 0; i < xRows; i++) {
51  for (size_t j = 0; j < xCols; j++)
52  std::cout << x.data[i * xCols + j] << " ";
53  std::cout << std::endl;
54  }
55
56  // Start a MATLAB Engine process using engOpen
58  if (!(ep = engOpen(""))) {
59  fprintf(stderr, "\nCan't start MATLAB engine\n");
60  return EXIT_FAILURE;
61  }
63
64  // Copy the contents of ViSP matrix to the MATLAB matrix variable T
66  memcpy((void *)mxGetPr(T), (void *)x.data, xRows * xCols * sizeof(double));
68
69  // Place the variable T into the MATLAB workspace
71  engPutVariable(ep, "Tm", T);
73
74  // Determine the sum of each column of input matrix x
75  // ViSP matrix is row-major and MATLAB matrix is column-major, so transpose the matrix T before evaluation
77  engEvalString(ep, "Dm = sum(Tm');");
79
80  // Get the variable D from the MATLAB workspace
82  D = engGetVariable(ep, "Dm");
84
85  // Copy the contents of MATLAB variable D to local variable res
87  memcpy((void *)res, (void *)mxGetPr(D), sizeof(res));
89
90  // Display output data to the user
91  std::cout << std::endl << "MATLAB Output Matrix (Column-wise sum):" << std::endl;
92  for (size_t i = 0; i < resCols; i++)
93  std::cout << res[i] << " ";
94  std::cout << std::endl;
95
96  // Wait until user exits