Access workspace variable from function within class

8 views (last 30 days)
I have a table (DataTable) stored in a .mat file (Data.mat) that I want to be able to access in functions within a few different classes. I have a test class that stores a set of indices that correspond to rows in DataTable, and I would like to retrieve the values in these rows from a particular column of DataTable as a dependent property:
classdef testClass
properties
Indices double
end
properties (Dependent)
Values double
end
methods
function obj = testClass(ind)
obj.Indices = ind;
end
function val = get.Values(obj)
load Data.mat
val = DataTable{obj.Indices,1};
end
end
end
However, I will be changing the indices and accessing new values many times, and I don't want to have to load Data.mat every time. What I would like to be able to do is load Data.mat file once in a setup script and then access DataTable within testClass without loading it again. Two potential methods I'm aware of are to create a global variable for DataTable in my setup script, or to use evalin, but both of these seem to be discouraged. I'm wondering if there's another best practice for accomplishing something like this.

Accepted Answer

Steven Lord
Steven Lord on 10 Feb 2017
Add a private or protected property to your class using the Access attribute on your properties block. In the constructor of the object, load the data and store it in the private/protected property. When you need to access it, do so from the private/protected property not the disk.
  3 Comments
Jonathan Schmid
Jonathan Schmid on 23 Mar 2019
Can you give an example of how to achieve that?
I.e., not having to write:
classdef Foobar
properties(Constant = true)
something = 5
end
end
But instead being able to write:
data = 5; % perhaps loaded from a file, also needed for other purposes
classdef Foobar
properties(Constant = true)
something % have the data ("5") be assigned to here somehow
end
methods
function this = Foobar(something)
% perhaps through the constructor?
end
end
end

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!