Multiple instances of function with persistent variables

19 ビュー (過去 30 日間)
Y
Y 2014 年 11 月 29 日
コメント済み: Image Analyst 2014 年 11 月 29 日
Hi, I have a function with persistent variables.
Is there anyway to run multiple instances of the function with different persistents?
The function is, and must be, Codegen compatible.
Thanks.

回答 (1 件)

Image Analyst
Image Analyst 2014 年 11 月 29 日
編集済み: Image Analyst 2014 年 11 月 29 日
Yes, but that's called a "class". A class is an object that has methods (functions) and properties (variables). Look up how to create one. Each "instance" of the class has its own private set of variable/property values that can be different than in other instances of the class. And they stick around while you're not referring to the class and doing other things, so they're like persistent variables. They will have the same values when you get back to using them.
  3 件のコメント
Image Analyst
Image Analyst 2014 年 11 月 29 日
編集済み: Image Analyst 2014 年 11 月 29 日
Why can't you just copy your functions into the class's m-file? If not, then just make a method with the same name as your function and, as long as that function is on the search path, your method should call the same function as long as your function is called inside the method.
Attached is an example of a class, if you need one (though it's probably somewhat complicated for you). You can of course make a much simpler one.
Image Analyst
Image Analyst 2014 年 11 月 29 日
Here's a simplified version:
classdef clsUserSettings
%USERSETTINGS Summary of this class goes here
% Detailed explanation goes here
properties (Access = private)
MyVariable= '';
TestFolder = '';
end
properties
UserSettings;
end
methods
%======================================
% Constructor to take folders and set up properties.
function US = clsUserSettings(macroFolder, testFolder)
% Set up private variables.
MyVariable = newMacroFolder;
TestFolder = newTestFolder;
end
% =============================================
% Method to take folders and set up properties.
function US = func1(myInputVariable)
fprintf('In func1\n');
% Call other func1() in a separate file.
US = func1(myInputVariable);
% Assign the public property
UserSettings.US = US;
end
end % Of the methods declarations
end % Of class definition.
That is just one example of how you could do it.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by