1

Is there a native way to create Static properties in Matlab?

Edit: This question refers to Matlab 2016b.

The code seems to behave differently in earlier versions of matlab (specifically r2014a), and the explanation is here https://www.mathworks.com/matlabcentral/newsreader/view_thread/171344/#/439111 aliasing Static with Constant. This is no longer the case, and in 2016B, Static is not supported.

I want to do something like

classdef A < handle
    properties(Static)
        prop
    end
    methods
        function [] = foo()
            disp(A.prop);
        end
    end
end

a1 = A;
a2 = A;
A.prop = 333;
a1.foo();%333
a2.foo();%333

This gives an error: The Static attribute is invalid on properties. Use Constant instead

Obviously, I don't want Constant, because I need to change the property prop

How can I achieve such behavior with some easy-to-write code?

I saw the workaround that uses a static method that has a persistent variable https://www.mathworks.com/help/matlab/matlab_oop/static-data.html

classdef StoreData
   methods (Static)
      function out = setgetVar(data)
         persistent Var;
         if nargin
            Var = data;
         end
         out = Var;
      end
   end
end

but this seems extremely unclean to me.

Is there a clean way to do this?

What I want eventually, is to create a Builder inner class for my class, but let's start with just a static property

Thanks.

Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • You could use a workspace for your class, variables in it would behave and could be used like static class-variables. However this isn't cleaner than the approach using a static method. – Y.S Mar 21 '17 at 10:10
  • http://stackoverflow.com/questions/6450204/how-to-obtain-static-member-variables-in-matlab-classes – Hadi Mar 21 '17 at 10:35
  • https://www.mathworks.com/help/matlab/matlab_oop/static-data.html – Hadi Mar 21 '17 at 10:35
  • Unfortunately the static method with a persistent variable is really the only way to accomplish this. – Suever Mar 21 '17 at 12:06

0 Answers0