Search code examples
performancematlabstructcellidentifier

Using non-continuous integers as identifiers in cells or structs in Matlab


I want to store some results in the following way:

Res.0 = magic(4);      % or Res.baseCase = magic(4);
Res.2 = magic(5);      % I would prefer to use integers on all other
Res.7 = magic(6);      % elements than the first.
Res.2000 = 1:3;

I want to use numbers between 0 and 3000, but I will only use approx 100-300 of them. Is it possible to use 0 as an identifier, or will I have to use a minimum value of 1? (The numbers have meaning, so I would prefer if I don't need to change them). Can I use numbers as identifiers in structs?

I know I can do the following:

Res{(last number + 1)} = magic(4);    
Res{2} = magic(5);
Res{7} = magic(6);
Res{2000} = 1:3;

And just remember that the last element is really the "number zero" element.

In this case I will create a bunch of empty cell elements [] in the non-populated positions. Does this cause a problem? I assume it will be best to assign the last element first, to avoid creating a growing cell, or does this not have an effect? Is this an efficient way of doing this?

Which will be most efficient, struct's or cell's? (If it's possible to use struct's, that is).

My main concern is computational efficiency.

Thanks!


Solution

  • As an alternative to EitanT's answer, it sounds like 's map containers are exactly what you need. They can deal with any type of key and the value may be a struct or cell.

    EDIT:

    In your case this will be:

    k = {0,2,7,2000};
    Res = {magic(4),magic(5),magic(6),1:3};
    ResMap = containers.Map(k, Res)
    
    ResMap(0)    
    ans =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1