initializing a 2d array, each element is a list?

Tag: arrays , matlab Author: h2o123123 Date: 2011-10-09

So, what I am trying to do is create a variable that holds 50 lists/arrays. Accessing an element in this variable would return one of the lists. If there are no elements at a given index, I would like it to return [].

My logic to initialize this would be something like:

spectrum_map=[];
for n=1:spectrum_blocks
    spectrum_map=[spectrum_map,[]];
end

However, after doing so, I simply get an empty matrix:

spectrum_map =

     []

What I want to see is something like:

spectrum_map =

     []  []  []  []  [] ....

That way, if I were to access spectrum_map(2), I would see that it is empty. However, instead I would get an error that the index exceeds matrix dimensions.

Is there some other way to do what I am trying to achieve?

Best Answer

You can get the effect you're looking for if you use a cell array instead of a matrix.

spectrum_map = cell( 1, 50 );
spectrum_map{50}

ans =

     []

If you need to convert back to a matrix later (to perform some math on it, for instance) you can use the cell2mat function.