How to create array of objects part of another object?

조회 수: 4 (최근 30일)
yaseen Ahmed
yaseen Ahmed 2018년 4월 20일
답변: Alexander James 2020년 6월 8일
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