MATLAB Answers

Access workspace variable from function within class

25 ビュー (過去 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 件のコメント
Luis Ruiz
Luis Ruiz 2020 年 7 月 15 日
An example is needed here.

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

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by