guanglei
guanglei

Reputation: 176

Construct an array of objects in MATLAB

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?

Upvotes: 2

Views: 315

Answers (2)

Sam Roberts
Sam Roberts

Reputation: 24127

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.

Upvotes: 0

zigzag
zigzag

Reputation: 415

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.

Upvotes: 1

Related Questions