How to use for loop to set properties' attributes in MATLAB class?
5 次查看(过去 30 天)
显示 更早的评论
I want to use the following loop to set properties' attributtes inside a class. Essentially it needs to store a struct as a class attribute. But when I put the following inside the class properties, its showing error.
Total_Grids = 100;
Grid(Total_Grids) = struct();
G = 1;
for i = 1:this.XGrid
for j = 1:this.YGrid
Grid(G).X = (this.GridSize/2)+ (j-1)*(this.GridSize); % x pos of each grid centre
Grid(G).Y = (this.GridSize/2)+ (i-1)*(this.GridSize); % y pos of each grid centre
G = G + 1;
end
end
Profits = randi([0,20],100,1); % profit of each grid, 100 grids are there
G = 1;
for i = 1:Total_Grids
Grid(G).Profit = Profits(G); % stored in Grid structure
G = G+1;
end
How and where to write it inside the class definition? I see normally the attributes are written like the following. Its not even using semicolon at the end of each attribute. How do I write a loop like the above here?
Thanks.
classdef CartPoleEnvironment < rl.env.MATLABEnvironment
%CARTPOLEENVIRONMENT: Template for defining custom environment in MATLAB.
%% Properties (set properties' attributes accordingly)
properties
% Specify and initialize environment's necessary properties
% Acceleration due to gravity in m/s^2
Gravity = 9.8
% Mass of the cart
CartMass = 1.0
%....and so on
end
3 个评论
采纳的回答
Matt J
2020-11-18
编辑:Matt J
2020-11-18
You cannot put a for loop or other complex code inside a properties block. If you wish, you can set a default value for a property with the following function call syntax, as long as the function defaultProp1() requires no inputs. Otherwise, you must initialize the property in the constructor.
classdef myclass
properties
prop1=defaultProp1()
end
end
function value=defaultProp1()
...
end
Here defaultProp1() can be defined anywhere that is visible to the classdef file, but a good place to put it would be in the classdef file as a class-related function.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!