Visual Servoing Platform  version 3.5.0 under development (2022-02-15)
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 <stdlib.h>
7 #include <stdio.h>
8 #include <string.h>
10 #include <matrix.h>
11 #include <engine.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; x[0][1] = 2; x[0][2] = 3;
21  x[1][0] = 4; x[1][1] = 5; x[1][2] = 6;
22  x[2][0] = 7; x[2][1] = 8; x[2][2] = 9;
24  int xCols = x.getCols();
25  int xRows = x.getRows();
26 
28  // MATLAB Engine
29  Engine *ep;
30 
31  // MATLAB array to store input data to MATLAB
32  mxArray *T = mxCreateDoubleMatrix(xRows, xCols, mxREAL);
33 
34  // MATLAB array to store output data from MATLAB
35  mxArray *D = NULL;
37 
38  // Temporary variable to hold Output data
39  double res[3];
40  int resCols = 3;
41 
42  // Display input data to the user
43  std::cout << "ViSP Input Matrix:" << std::endl;
44  for (size_t i = 0; i < xRows; i++) {
45  for (size_t j = 0; j < xCols; j++)
46  std::cout << x.data[i * xCols + j] << " ";
47  std::cout << std::endl;
48  }
49 
50  // Start a MATLAB Engine process using engOpen
52  if (!(ep = engOpen(""))) {
53  fprintf(stderr, "\nCan't start MATLAB engine\n");
54  return EXIT_FAILURE;
55  }
57 
58  // Copy the contents of ViSP matrix to the MATLAB matrix variable T
60  memcpy((void *)mxGetPr(T), (void *)x.data, xRows * xCols *sizeof(double));
62 
63  // Place the variable T into the MATLAB workspace
65  engPutVariable(ep, "Tm", T);
67 
68  // Determine the sum of each column of input matrix x
69  // ViSP matrix is row-major and MATLAB matrix is column-major, so transpose the matrix T before evaluation
71  engEvalString(ep, "Dm = sum(Tm');");
73 
74  // Get the variable D from the MATLAB workspace
76  D = engGetVariable(ep, "Dm");
78 
79  // Copy the contents of MATLAB variable D to local variable res
81  memcpy((void *)res, (void *)mxGetPr(D), sizeof(res));
83 
84  // Display output data to the user
85  std::cout << std::endl << "MATLAB Output Matrix (Column-wise sum):" << std::endl;
86  for (size_t i = 0; i < resCols; i++)
87  std::cout << res[i] << " ";
88  std::cout << std::endl;
89 
90  // Wait until user exits
91  std::cout << std::endl << "Hit return to quit\n" << std::endl;
92  fgetc(stdin);
93 
94  // Free memory, close MATLAB Engine and Exit
96  mxDestroyArray(T);
97  mxDestroyArray(D);
98  engEvalString(ep, "close;");
99  engClose(ep);
101 
102  return EXIT_SUCCESS;
103 }
Implementation of a matrix and operations on matrices.
Definition: vpMatrix.h:153