Using MATLAB Coder with a singleton class accessing Constant property returns error "Initial values of class types can only be used for reading properties"

11 vues (au cours des 30 derniers jours)
I am trying to use a singleton model for a class and would like to generate C code from some MATLAB code that uses this class. However, it seems to be returning the error "??? Initial values of class types can only be used for reading properties.". Below, I provide a small example demonstrating the issue. It is unclear what exactly the issue is given the error is occuring on the line trying to access the instance property (obj = SingletonClass.instance), and this line is reading a constant property of the class.
I have two questions:
  • Could you help me understand the meaning of this error and why it is occuring?
  • Is there a easy fix to this while still following the singleton model for the class?
Class definition:
classdef SingletonClass < handle
properties (Access = protected)
data (1,1) double = 5;
end
properties (Constant, Access = private)
instance (1,1) SingletonClass = SingletonClass();
end
methods (Access = private)
function this = SingletonClass()
% Constructor
end
end
methods (Static, Access = public)
function obj = Instance()
% Get singleton instance
obj = SingletonClass.instance;
end
end
methods (Access = public)
function out = test(this, val)
% Test code
out = this.data + val;
end
end
end
The function I am trying to use coder on:
function out = myfunction(val) %#codegen
obj = SingletonClass.Instance();
out = obj.test(val);
end
Codegen script:
val = double(0);
codegen myfunction -args {val}
  2 commentaires
Mukund Sankaran
Mukund Sankaran le 27 Oct 2022
Modifié(e) : Mukund Sankaran le 27 Oct 2022
For your second question, you could rewrite your static method to use persistent variables, like below, and that should work
classdef SingletonClass < handle
properties (Access = protected)
data (1,1) double = 5;
end
methods (Access = private)
function this = SingletonClass()
% Constructor
end
end
methods (Static, Access = public)
function obj = Instance()
% Get singleton instance
persistent instance
if isempty(instance)
instance = SingletonClass();
end
obj = instance;
end
end
methods (Access = public)
function out = test(this, val)
% Test code
out = this.data + val;
end
end
end
Mukund Sankaran
Mukund Sankaran le 28 Oct 2022
As regards your question #1, the error message is trying to say that you are only allowed to read the properties of "instance". For example, you are allowed to write an expression like this that reads the "data" property of "instance".
someVar = SingletonClass.instance.data + 1;

Connectez-vous pour commenter.

Réponses (0)

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by