我将在MATLAB中同时运行20个函数/过程来分析一个大数据集。每个函数都访问这个大数据集的一部分。缓存是我的主要组件,我需要向您展示MATLAB可以使用缓存能力。我想:
你能告诉我怎么可能吗?我需要一些提示。
发布于 2014-07-28 18:33:39
检查persistent变量在MatLab (和mlock函数)中的文档。它部分涵盖了你所需要的东西。但是,在访问持久变量以及在更新函数源文件时清除持久性变量这一事实方面,您将面临相当大的问题。
我建议为您的缓存使用文件(当然,如果我正确理解您的意思)。例如,您可以从这种方法开始(我假设每个函数都位于单独的*.m文件中)
function CacheFileName = GenerateCacheFileName(Caller)
CacheFileName = sprintf('%s.cache.mat',Caller);
% you may use any alogrithm that makes sense for you
% but keep the MAT extension for the simple syntax of LOAD function
end
function Data = LoadCachedData(Caller)
% Generate cache file name for current function
CacheFileName = GenerateCacheFileName(Caller);
if exist(CacheFileName,'file')==2
% load cache file if it exists
RawData = load(CacheFileName);
Data = RawData.CacheStructure;
else
% or initialize the cahce with empty structure
Data = struct;
end
end
function DoSomethingUsingCache(arguments)
% Generate cache file name for current function
CacheFileName = GenerateCacheFileName(mfilename);
% Load cached data
if exist(CacheFileName,'file'==2)
% load cache file if it exists
CacheStructure = load(CacheFileName);
else
% or initialize the cahce with current datestamp
CacheStructure.Created = now;
end
% do what you need here
% Save data to cache for later use
save(CacheFileName,'CacheStructure');
end如果您需要从其他函数加载一些数据,只需这样做:
function DoSomethingUsingCacheOfOtherFunction(arguments)
% Load chached data of other function
CacheStructure2 = LoadCachedData('DoSomethingUsingCache');
% do what you need here
if isfield(CacheStructure,'Param4')
CacheStructure.Param4 = CacheStructure.Param4 + 10;
else
CacheStructure.Param4 = 0;
end
% you may also update the cache for other function if you need
save(CacheFileName2,'CacheStructure2');
end显然,应该正确设计这种方法,否则MatLab将花费大部分时间加载/保存您的数据。
原则上,这种方法可以作为具有set/get方法的MatLab类来表示,以获得更简单的代码。如果在根命名空间中创建对象,则可以将其用作“缓存的数据管理器”。
https://stackoverflow.com/questions/24999184
复制相似问题