Loading and unloading data files
13 次查看(过去 30 天)
显示 更早的评论
In the applications I'm working on I typically store information in .mat files which I then load several times throughout the application. I don't like passing this data through global variables so I end up loading the data several times. My question is does this data get saved into memory each time? Or does each load remove the previous version in memory? Additionally, do I need to close the file somehow?
Thanks, Jeff
0 个评论
采纳的回答
Walter Roberson
2013-5-31
编辑:Walter Roberson
2013-5-31
Data that is created in a workspace is removed once that function terminates (provided no reference to it is being held somewhere)
However, if you have a structure such as
A loads file and calls B
B calls C
C calls D
D loads file
D returns
C calls E
then the copy of the file that was loaded in D is discarded when D returns, but at the point that D does the load, there are multiple copies of the data (one in A) because A has not yet terminated.
You might want to consider storing the data as app data using setappdata(). Myself I would consider that to be equivalent to using a global variable (though one slightly less likely to be inadvertently changed.)
If you have a gui interface, you could use guidata()... which is setappdata() in disguise... which is at least in theory "local" to a figure() rather than being global, but most people treat it as being global, and about the only time most people deal with the fact that it is local is if they try to merge two GUIDE-created interfaces, and then they are likely to be cursing the fact that it is not completely global.
Anyhow...
3 个评论
Walter Roberson
2013-5-31
Right. But if you use one of the alternatives I mention, then there would usually be only a single copy of the actual storage, unless you changed one of the variables.
更多回答(1 个)
per isakson
2013-5-31
"does this data get saved into memory each time". I'm not sure I understand correctly. The system cache is affected and data are written to disk.
"Or does each load remove the previous version in memory?". The values of the Matlab variables are replaced each time. If the data are still in system cache that is used otherwise data are read from disk.
No, you don't need (and cannot) close the file explicitly.
Are you aware save( .... , '-v6' ) is faster?
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!