Access workspace variable from function within class

12 vues (au cours des 30 derniers jours)
Josh
Josh le 10 Fév 2017
Commenté : Luis Ruiz le 15 Juil 2020
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.

Réponse acceptée

Steven Lord
Steven Lord le 10 Fév 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 commentaires
Jonathan Schmid
Jonathan Schmid le 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
Luis Ruiz
Luis Ruiz le 15 Juil 2020
An example is needed here.

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by