MATLAB Answers

How to create array of objects part of another object?

38 views (last 30 days)
yaseen Ahmed
yaseen Ahmed on 20 Apr 2018
Answered: Guillaume on 20 Apr 2018
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

  0 Comments

Sign in to comment.

Answers (1)

Guillaume
Guillaume on 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

  0 Comments

Sign in to comment.

Sign in to answer this question.