dynamic
dynamic

Reputation: 48111

Vector of objects in Matlab without knowing dimension

I have this code:

allObjects=[]
for i=1:100
   allObjects(end+1) = MyObject();   % push the object to the end of my vector
end

But this prints:

Conversion to double from MyObject is not possible.

Same thing if i declare allObjects as a cell array

 allObjects = {}

How can I have a vector of objects in Matlab, consider I can't know how many objects I will need to store?

Upvotes: 3

Views: 2012

Answers (2)

Sam Roberts
Sam Roberts

Reputation: 24127

allObjects = MyObject.empty will give you an empty array of objects of class MyObject. empty is a Public Static method of all non-abstract classes designed for this purpose. Type doc empty for more information.

Upvotes: 6

dynamic
dynamic

Reputation: 48111

The solution is to do

allObjects=[MyObject]

This will tell matlab that allObjects is a vector of MyObject

The only problem is that the real objects will start from index 2 (because you push an element with end+1)

Upvotes: 2

Related Questions