Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. matlab = new MLApp.MLAppClass();
  2.  
  3. object myObject;
  4.  
  5. matlab.GetWorkspaceData("myVariable", "base", out myObject);
  6.  
  7. matlab = new MLApp.MLAppClass();
  8.  
  9. object myObject = new object();
  10.  
  11. matlab.GetWorkspaceData("myVariable", "base", out myObject);
  12.  
  13. using System;
  14.  
  15. namespace CSharp_matlab_com
  16. {
  17. class Program
  18. {
  19. static void Main(string[] args)
  20. {
  21. MLApp.MLAppClass matlab = new MLApp.MLAppClass();
  22.  
  23. // create variables: a_0, a_1, ..., a_4
  24. for (int k = 0; k < 5; k++) {
  25. matlab.Execute(string.Format("a_{0} = rand(2);", k));
  26. }
  27.  
  28. // retrieve variables from MATLAB and print their contents
  29. object a;
  30. for (int k = 0; k < 5; k++) {
  31. // current variable name
  32. string varname = string.Format("a_{0}", k);
  33.  
  34. // get data array
  35. a = null; // without this line, an exception is thrown!
  36. matlab.GetWorkspaceData(varname, "base", out a);
  37.  
  38. // print contents
  39. var arr = (double[,]) a;
  40. Console.WriteLine("nndims(a) = {0}, numel(a) = {1}", arr.Rank, arr.Length);
  41. for (int i = 0; i < arr.GetLength(0); i++) {
  42. for (int j = 0; j < arr.GetLength(1); j++) {
  43. Console.WriteLine("{0}[{1},{2}] = {3}", varname, i, j, arr[i,j]);
  44. }
  45. }
  46. }
  47. }
  48. }
  49. }
  50.  
  51. ndims(a) = 2, numel(a) = 4
  52. a_0[0,0] = 0.251806122472313
  53. a_0[0,1] = 0.617090884393223
  54. a_0[1,0] = 0.290440664276979
  55. a_0[1,1] = 0.265280909810029
  56.  
  57. ...
  58.  
  59. ndims(a) = 2, numel(a) = 4
  60. a_4[0,0] = 0.425259320214135
  61. a_4[0,1] = 0.16148474431175
  62. a_4[1,0] = 0.312718886820616
  63. a_4[1,1] = 0.178766186752368
  64.  
  65. public object GetData(string name)
  66. {
  67. object data;
  68. mlApp.GetWorkspaceData(name, "base", out data);
  69.  
  70. return data;
  71. }
  72.  
  73. public T GetData<T>(string name)
  74. {
  75. object data;
  76. mlApp.GetWorkspaceData(name, "base", out data);
  77.  
  78. if (data == null)
  79. return default(T);
  80.  
  81. if (data is T)
  82. return (T)data;
  83. else
  84. throw new InvalidCastException($"The variable '{name}', of type '{data.GetType().Name}' cannot be casted to type '{typeof(T).Name}'.");
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement