How to create array of objects part of another object?

2 visualizzazioni (ultimi 30 giorni)
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

Risposte (2)

Guillaume
Guillaume il 20 Apr 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 il 8 Giu 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;

Categorie

Scopri di più su Construct and Work with Object Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by