MATLAB Answers

Loading from Workspace via string

17 views (last 30 days)
Daniel Schmidt
Daniel Schmidt on 6 Aug 2019
Commented: Daniel Schmidt on 6 Aug 2019
Hey,
I am trying to use the load function and point assignement to load data using strings.
Currently I am using a code like this, to access variables via their string names.
a=load('filename.mat')
x=a.('variable_name')
But it can get annoying and time intensive to load the mat file seperately.
Is it possible to skip the a=load part and just to assign x directly through the workspace?
I want basically something like this:
x=workspace.('variable_name');
Thank you.

  2 Comments

Adam
Adam on 6 Aug 2019
How do you expect to get your data from file into the workspace if you skip the loading part?
Daniel Schmidt
Daniel Schmidt on 6 Aug 2019
The data is allready loaded into the workspace beforehand.

Sign in to comment.

Accepted Answer

Rik
Rik on 6 Aug 2019
The matfile function has an interface similar to what you're looking for. You do need to be careful with indexing if you want to prevent loading of the entire variable, but it will allow you to mostly keep the contents of the mat files on the disk instead of memory.
Note that there is a trade-off: this is slower to work with than having the variables in memory, but it might save time and memory when retrieving the variable if you have large variables stored in the mat file and are not using those.

  3 Comments

Daniel Schmidt
Daniel Schmidt on 6 Aug 2019
Very nice function thank you. It will come in handy for later purposes.
But it can't access variables via other variables.
If I want to load a string by the name "text", it can be loaded by:
m=matfile('filename');
data = m.text;
but it doesn't work if the name of the variable is in a string.
This does not work:
variable_name = "text";
m=matfile('filename');
data = m.variable_name;
And that is what I need.
The load option seems to be the best way for now.
Rik
Rik on 6 Aug 2019
It seems to me your described situation invites bad habits like numbered variables, but the code below does work (at least on my copy of R2019a).
variable_name = "text";
m=matfile('filename');
data = m.(variable_name);
It works for strings and char arrays, just like accessing fields of a struct.
Daniel Schmidt
Daniel Schmidt on 6 Aug 2019
Thanks, I got it.
I still can't read directly out of the workspace, but it is a nice workaround with the matfile function, which (hopefully) reduces the computing time and effort.
Thanks a lot to everyone

Sign in to comment.

More Answers (0)

Sign in to answer this question.


Translated by