Access workspace variable from function within class

12 ビュー (過去 30 日間)
Josh
Josh 2017 年 2 月 10 日
コメント済み: Luis Ruiz 2020 年 7 月 15 日
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.

採用された回答

Steven Lord
Steven Lord 2017 年 2 月 10 日
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 件のコメント
Jonathan Schmid
Jonathan Schmid 2019 年 3 月 23 日
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 2020 年 7 月 15 日
An example is needed here.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by