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 (최근 30일)
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
Mukund Sankaran
Mukund Sankaran 2022년 10월 27일
편집: Mukund Sankaran 2022년 10월 27일
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 2022년 10월 28일
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;

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB Classes에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by