Home > Enterprise >  reorganize keys of containers map
reorganize keys of containers map

Time:07-27

I create by iteration with a for loop a container map on matlab whose keys are for example :

keys(tab) = 1x3 cell array
{'long_Kinn'} {'long_pro'} {'long_tal'}

I would like to know if it is possible to bypass the alphanumeric ordering of the keys and reorganize them as : ?

keys(tab) = 1x3 cell array
{'long_pro'} {'long_tal'} {'long_Kinn'}

Matlab version 2020a

CodePudding user response:

A map is, by definition, an unordered container. If the order is important, use an array, not a map.

For example, if you currently map those keys to values A, B and C, create a cell array as follows:

tab = {};
tab{:, end   1} = {'long_pro'; A};
tab{:, end   1} = {'long_tal'; B};
tab{:, end   1} = {'long_Kinn'; C};

...Which of course you’d do in your loop. Now insertion order is preserved.

Appending to an array is not recommended, but this will be faster than adding to a containers.Map anyway. The orientation of the cell array above was chosen to make appending most efficient.

If you need to use your cell array for lookup, you can do:

value = tab{2, strcmp(tab(1,:), key)};

This is not as pretty as lookup in a map, but it works just as fine as long as you don’t have a humongous amount of keys in your container.


Alternatively, consider using a table object, since you seem to be working with tabular data.

  • Related