2

I am trying to initialize an empty array which itself contains 5 empty arrays. But matlab seems to just create a simple empty array variable instead. Following are the two syntaxes I have tried. Any ideas if it is possible in matlab?

bins = [ []; []; []; []; []  ];

bins = repmat([], 5, 1)

3 Answers 3

4

deal is a good function for such an assignment:

[bins{1:5}] = deal([]);

This creates a cell array bins, where each element bins{i} contains an empty array.

Sign up to request clarification or add additional context in comments.

1 Comment

How about fully pre-allocating a 2D array? In that case, the [] inside the deal would itself need to be m empty spaces. Initializing it with empty members instead of using zeros is better if there is a chance what is going into the array would itself have a value of 0 (otherwise you can't distinguish between a zero in the data or an error stopping you from assigning to that position).
3

MATLAB only has matrices, i.e. (potentially multidimensional) arrays of numerical types (or characters or logical values). To group other structures in one variable, try a cell array, e.g.

bins = { []; []; []; []; []  };

You then have to access elements of the outer array with curly brackets, e.g. bins{2} instead of bins(2).

Comments

0

Another trick to initialize this:

>> bins = {}      %# just to make sure `bins` wasn't used before
>> bins{5} = []
bins = 
    []    []    []    []    []

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.