I am attempting to make use of a persistent variable within a class method. However, invoking the method from different instances is producing incorrect results. Here is a simple case of what I mean:
CLASS:
classdef MYCLASS < handle properties(GetAccess = 'private', SetAccess = 'private') m_Count end methods(Access = 'public') %constructor
function obj = MYCLASS obj.m_Count = 0; end function out = DO_SOMETHING_MOUSE(obj) persistent n if isempty(n) n = 0; end n = n+1; out = n; end function out = DO_SOMETHING_CAT(obj) obj.m_Count = obj.m_Count + 1; out = obj.m_Count; end end end
MATLAB FILE:
clear allclear classesclcInstance_A = MYCLASS;Instance_B = MYCLASS;n = Instance_A.DO_SOMETHING_MOUSEn = Instance_B.DO_SOMETHING_MOUSEn = Instance_A.DO_SOMETHING_CATn = Instance_B.DO_SOMETHING_CAT
COMMAND WINDOW RESULTS:
a = 1b = 2a = 1b = 1>>
Here you can see that we call the DO_SOMETHING_MOUSE method from two different instances of the class, yet, the value of the persistent variable "n" was somehow shared between instances.
The result we should have gotten is that which was illustrated by the call to the DO_SOMETHING_CAT method. Each instance had it's own value correctly stored.
What's wrong?
Best Answer