zebra
zebra

Reputation: 6531

How to create a list of arbitrarily sized lists

I'm trying to create a container that has 3 lists within it, where each list is an arbitrarily sized list of arbitrarily sized lists. Here is my train of thought on what I would be doing (not very experienced in Matlab, so there's probably a more elegant way of doing this)

my_data = [[] [] []];

for m = 1 : M
   list1 = [];
   list2 = [];
   list3 = [];

   for n = 1 : N
      if something holds
         list1 = [list1 ftn(n)];
         list2 = [list2 ftn2(n)];
         list3 = [list3 ftn3(n)];
      end
   end

   if something else holds
      my_data(1) = [my_data(1) list1];
      my_data(2) = [my_data(2) list2];
      my_data(3) = [my_data(3) list3];
   end
end

This code doesn't actually run though... How do I do something like this in Matlab?

Upvotes: 0

Views: 99

Answers (1)

Danica
Danica

Reputation: 28846

This is what cell arrays are for. Matlab doesn't let you do non-rectangular regular arrays (as you've discovered), but cell arrays let you do arrays of general objects, including standard arrays.

my_data = {{} {} {}};

for m = 1 : M
    list1 = [];
    list2 = [];
    list3 = [];
    for n = 1 : N
        if something
            list1 = [list1 something];
            list2 = [list2 something];
            list3 = [list3 something];
         end
    end

    if something
        my_data{1}{end+1} = list1;
        my_data{2}{end+1} = list2;
        my_data{3}{end+1} = list3;
    end
end

Upvotes: 2

Related Questions