1
votes

I'd like to implement a class which returns the data located in a precalculated data file, e.g.

classdef myConstants
  properties ( Constant )
    const1 = load('consts.mat', 'const1');
  end
end

However, I want the file consts.mat to lie in the @myConstants folder which is on the MATLAB path, so I cannot (and should not) hard-code the location.

So how can I instruct load to use the file @myConstants\consts.mat independently of @myConstants actual location?

edit I realized if the folder @myConstants lies on the MATLAB path, load consts.mat works globally. So, the code I wrote already works perfectly fine, but consts.mat is not only globally accessible, one also has to pay attention to name collisions if other classes provide their own consts.mat - which is why I don't post this as an answer, I'd still prefer a solution that does not bear this potential bug source.

2
As I understand it, @-folders should not be in the MATLAB path to begin with, which is perhaps the problem. - Will
@Will Why is that? Should one use +packages instead? - Tobias Kienzler

2 Answers

2
votes

Place consts.mat in the directory @myConstants\private. You may also wish to do this:

const1 = getfield( load( 'consts.mat', 'const1' ), 'const1' );

because LOAD returns a structure with fields named for the values loaded.

1
votes
const1 = load([fileparts(mfilename('fullpath')) filesep 'consts.mat'], 'const1');

does the trick, but it does not hide consts.mat