How to use for loop to set properties' attributes in MATLAB class?
조회 수: 6 (최근 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!