How to create array of objects part of another object?

4 次查看(过去 30 天)
I'm quite new to doing OOP in Matlab. Here I'm trying to create an array of objects as part of another object and I get this error "The following error occurred converting from RobotCreature to double: Conversion to double from RobotCreature is not possible."
classdef Generation
%UNTITLED Summary of this class goes here
% Detailed explanation goes here
properties
size
population
end
methods
function obj = Generation(size, kp, kd)
obj.size = size;
for i = size:-1:1
obj.population(i) = RobotCreature(kp, kd);
end
end
end
end

回答(2 个)

Guillaume
Guillaume 2018-4-20

Since you haven't specified anything for population in your properties definition, it is initialised as an empty array of double. So when you try to grow the population array in the constructor matlab is not happy since you're trying to assign a RobotCreature to an array of double.

The easiest fix: create population as an empty array of RobotCreature:

      properties
          size
          population = RobotCreature.empty
      end

Alexander James
Alexander James 2020-6-8
I'm not sure if this has changed in version 2019b but Guillaume's answer needed tweaking for his fix to work in my code, adding the object.empty in properties created a validation function not recognised error for me. If I added this line to the constructor however this solved the problem for me and allowed me to add object to the forest list.
classdef Forest
% Creation of the Forest class
properties (Access = public)
forest
road
end
methods
function newForest = Forest(geometry,road)
newForest.forest = Tree.empty;

类别

Help CenterFile 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!

Translated by