How to load mat file located in a package folder (.../+fold​er/matfile​.mat)

2 views (last 30 days)
Folder structure:
/+pkg
/+pkg/cls.m (that's a classdef)
/+pkg/matfile.mat
From within the constructor of cls.m, I want to do: content = load('matfile.mat');
I've tried load('matfile'), load('pkg.matfile'), load('pkg.matfile.mat')... nothing works.
Is there a way to do this cleanly?

Answers (1)

per isakson
per isakson on 22 Dec 2017
Given
...\+pkg\cls.m
...\+pkg\matfile.mat
Try this
>> obj = pkg.cls
obj =
cls with properties:
mat: [1x1 struct]
where
classdef cls < handle
properties
mat
end
methods
function this = cls()
folder = fileparts( which('pkg.cls') );
this.mat = load( fullfile( folder, 'matfile.mat' ) );
end
end
end
  2 Comments
Walter Roberson
Walter Roberson on 22 Dec 2017
Wouldn't it be cleaner to use mfilename to get the file name of the class definition file?
per isakson
per isakson on 22 Dec 2017
Edited: per isakson on 22 Dec 2017
Yes, it would!
I had forgotten that mfilename takes arguments. By itself, mfilename doesn't return the package name, only the name, cls.
Thus, replace
folder = fileparts( which('pkg.cls') );
by
folder = fileparts( mfilename('fullpath') );

Sign in to comment.

Categories

Find more on Software Development Tools in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!