Save text of script in .mat file?
18 次查看(过去 30 天)
显示 更早的评论
Is there a way of saving the text of the current script as a variable? I'd like to save this to a .mat file along with the other workspace variables created by the script. Even better, I'd like to save the current version of all user-written functions called by the script in .mat file.
Some context for why I want to do this:
I frequently run simulations in MATLAB and save the data to a .mat file, then change a couple of parameters in the simulation, or tweak the code slightly, and repeat. When the time comes to use the data, it is often hard to keep track of how each .mat file was generated. The parameter values are saved as long as I save the entire workspace, but what they mean --- or more generally, what the code was doing --- is not. I usually keep a log with notes about each .mat file to help me remember this information, but this is cumbersome and incomplete. It seems that saving the script as part of the .mat file would be an easier and more complete way to keep all the information about the data. I imagine this is a very common problem, so I'm wondering if there is a way to do this, or otherwise, if anyone has a good strategy for keeping the info about the data.
Thanks,
Peter
3 个评论
采纳的回答
Les Beckham
2023-10-16
I suppose that one option would be to read the file contents into a string array and save that to your mat file.
For example:
str = readlines('tic.m') % replace 'tic.m' with mfilename to read the current file
更多回答(2 个)
Steven Lord
2023-10-16
Rather than trying to put (potentially a large amount of) code in your MAT-file, why not create a struct or object with your parameters (with descriptive field and/or property names), pass that struct or object into your function, and have the function return a struct or object with the results of the analysis for those parameter values inside it?
John D'Errico
2023-10-16
Is it really a common problem? Not that I've ever seen any need for in 35 years of MATLAB use, nor in any question I can recall in almost as long a time spent answering questions in various forums.
This seems like a pain in the butt to do. Because then accessing the file in some sort of form you will store it, which in itself will not be very usable will not be trivial.
Why not just use a revision control system? Now all you need to save with the results is a version number. Instead of scripts, use functions. So now all you need to save are the parameters you will pass into those functions. Scripts are bad news anyway.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!