MATLAB Answers

Why isn't this file loading method working?

2 views (last 30 days)
Kieran Fung
Kieran Fung on 14 May 2021
Commented: DGM on 14 May 2021
I've had success in the past piecing together proper file strings name to call upon the right file name. Here I'm trying to compare saved data sets and plot their data series one at a time, since all data sets share the same variable names.
I figured I could just loop through each file name and plot their respective series independent of one another simply by using the 'hold on' syntax to keep previous data sets since all files of interest I want to compare all have the same variable names. That makes sense right? I would just grab one variable of a data set, plot it and hold on, and rewrite over the variable name for the next data set of interest.
I've attached a code screen shot for reference. The two files/datasets I'm working with right now can be seen in the current folder workspace. Like I've said, I've used this technique in the past but cannot recognize why the data sets are not being loaded.
Any advice would be appreciated!
  6 Comments
DGM
DGM on 14 May 2021
Someone can offer a more technically thorough explanation than I can, but if you do something like
load('mybigfilefullofstuff.mat');
y = x*2;
z = mean(y);
Prior to running, or at parse time, how does Matlab know anything about where x came from? It can't know how many other things are going to show up in the workspace until it actually loads the file at run time. It defeats a lot of the guidance that the code tools could give the person writing the code, and it leaves the possibility for all sorts of hard to detect/predict shenanigans to occur. What if one of the variables in that .mat file is called mean?
If you load into a struct:
S = load('mybigfilefullofstuff.mat');
y = S.x*2;
z = mean(y);
Matlab knows ahead of time that y is a function of a thing that came from S which came from load(). It knows that mean() isn't something that came from S.

Sign in to comment.

Answers (1)

DGM
DGM on 14 May 2021
Edited: DGM on 14 May 2021
myfilename is a string containing the filename
load(myfilename)
passes the string "theta_stuff_acoustics.mat" to load() (and should work if it's a valid filename)
load('myfilename')
passes the char vector 'myfilename' to load(), but there probably isn't any file called 'myfilename'

Community Treasure Hunt

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

Start Hunting!