Access workspace variable from function within class

조회 수: 13 (최근 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 CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by