2

Say I have defined a class house in MATLAB.

How could I construct an array of objects of class house, except the naive idea of loops?

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64
guanglei
  • 176
  • 2
  • 9
  • possible duplicate of this (http://stackoverflow.com/questions/2510427/how-to-preallocate-an-array-of-class-in-matlab) – Satish Chalasani Jul 17 '15 at 14:01
  • I think you'll need the loop somewhere. Either in the constructor or where you create the objects. Check out [this](http://ch.mathworks.com/help/matlab/matlab_oop/creating-object-arrays.html) in the Matlab-documentation. – Matt Jul 17 '15 at 14:06

2 Answers2

1

You can use houseArray = repmat(house, numHouses, 1) to create a column array of house structures. Change 1 to something else if you need an n by m structure array.

zigzag
  • 415
  • 3
  • 7
0

One way would be to create an individual object of class house, and then use repmat to copy that instance into all elements of a larger array.

Another way would be to create an array by assigning an object of class house to a later element - for example by saying myhouses(2,3) = house. This works in the same way as when you say mynumbers(2,3) = 2 - you get an array [0,0,0;0,0,2].

When you use that syntax, MATLAB needs to create a default value of house (in the same way as it fills the other elements of the numeric array with a default value of zero). To do that, it calls the constructor of house with zero input arguments - so you need to implement that constructor in such a way that, when called with zero inputs, it outputs a default instance of house.

A third option would be to implement your constructor in such a way that it could accept input arguments specifying the size of an output array, and then directly output an array of objects with that size.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64