Is it possible to create a persistent variable in a MATLAB function with an arbitrary data type? For example, I would like to create a persistent containers.Map variable in my MATLAB function. How can I do that?
2 Answers
All variables defined as persistent using the persistent keyword are initialized to an empty array of the double datatype. You can re-initialize them to whatever datatype you want by checking if they are empty using isempty and performing the initialization then. You can also check to ensure that it is a double just in case you don't want to force re-initialization if you have an empty containers.Map object.
function persist(key, value)
persistent container
if isa(container, 'double') && isempty(container)
container = containers.Map();
end
container(key) = value;
end
MATLAB class properties can be used for this, since they can be restricted to specific datatypes. For example:
classdef foo
properties
prop@char scalar = 'A' % will only accept char inputs, not numeric
end
end
Then every method that tries to update this.prop would fail if the provided values is of an incorrect type. If the update succeeds, you can update the persistent variable too.
This functionality was officially incorporated into R2017a, but an undocumented way has been known for a while now.
For further reading see this blog post.
double,charetc.) - the data-type is no longer arbitrary!, but rather very specific (or "enforced", as I put it). Of course your are free to do with your question what you want, but I think my edit helped clarify the intention better. - Dev-iL