Main Content

MathWorks.MATLAB.Types.MATLABWorkspace

.NET class to manage interactions with MATLAB base workspace variables

Since R2022b

Description

Namespace:

MathWorks.MATLAB.Types
Superclass:IReadOnlyDictionary

Method Summary

Public Methods

dynamic this["varname"]

Get or set the variable varname in the workspace.

int Count

Get the number of variables in the workspace.

System.Collections.Generic.IEnumerable<string> Keys

Get the names of the workspace variables, specified as an enumerable collection.

System.Collections.Generic.IEnumerable<dynamic> Values

Get the values of the workspace variables, specified as an enumerable collection.

bool ContainsKey(string key)

Determine if workspace contains the specified variable.

bool TryGetValue(string key, out dynamic value)

Determine if the specified key exists and get the value.

Examples

expand all

Create and use variables in the MATLAB® base workspace. For information about creating this C# example, see WorkspaceExample.cs in Test Your .NET Development Environment.

Create a workspace variable x using the MATLABWorkspace data type.

MATLABWorkspace workspace = eng.Workspace;
workspace["x"] = 3.14;

Create another workspace variable y using the eval function.

RunOptions opts = new RunOptions() { Nargout = 0 };
eng.eval(opts, "y = 'this is a char array';");

Display information about the MATLAB base workspace.

int numVars = workspace.Count;
Console.WriteLine("There are {0} variables in the MATLAB base workspace.", numVars);

string[] varNames = workspace.Keys.ToArray();
Console.WriteLine("  It contains these variables: {0}", string.Join(", ", varNames));

Display the workspace variables.

double valueOfX = workspace["x"];
string valueOfY = workspace["y"];
Console.WriteLine("  x == {0}", valueOfX);
Console.WriteLine("  y == \"{0}\"", valueOfY);

Query for the existence of specific variables.

Console.Write("Querying the value of x... ");
if (workspace.TryGetValue("x", out valueOfX))
    Console.WriteLine("x == {0}", valueOfX);
else
    Console.WriteLine("x does not exist in the workspace.");

Console.Write("Querying the value of z... ");
if (workspace.TryGetValue("z", out string valueOfZ))
    Console.WriteLine("z == {0}", valueOfZ);
else
    Console.WriteLine("z does not exist in the workspace.");

Exceptions

System.Collections.Generic.KeyNotFoundException

Specifying a variable that does not exist in the MATLAB base workspace.

System.ArgumentNullExceptionNull string is not a valid argument.

Version History

Introduced in R2022b