How to create array of objects part of another object?

7 visualizaciones (últimos 30 días)
yaseen Ahmed
yaseen Ahmed el 20 de Abr. de 2018
Respondida: Alexander James el 8 de Jun. de 2020
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

Respuestas (2)

Guillaume
Guillaume el 20 de Abr. de 2018

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 el 8 de Jun. de 2020
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;

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by