Search code examples
matlabhashoctavecell-array

Reverse struct in octave


I implemented a struct in octave like this:

words = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "};

hash = struct;
for word_number = 1:numel(words)
    hash = setfield(hash, words{word_number},word_number);
endfor

This is like a hashmap of the form : {'a':1,'b':2....}

I want the reverse form of this struct of the form : {1:'a',2:'b'.....}

Edit: I tried to reverse it but was getting the error because keys can't be integer in struct as pointed out by Mr. Divakar in the answers.

Thanks in advance.


Solution

  • Variable names or structure fieldnames must not start with numerals. If you are getting any error, it might be because of that. So, to avoid this issue, use a common keyword and append the numerals to it.

    If you prefer a no-loop approach -

    %// Declare the keyword that doesn't start with any numeral
    keyword = 'field_'
    
    %// This might be a more efficient way to create a cell array of all letters that 
    %// uses ascii equaivalent numbers
    words = cellstr(char(97:97+25)') 
    
    %// Set fieldnames
    fns = strcat(keyword,strtrim(cellstr(num2str([1:numel(words)]'))))
    
    %// Finally get the output
    hash = cell2struct(words, fns,1)
    

    Output -

    hash = 
         field_1: 'a'
         field_2: 'b'
         field_3: 'c'
         field_4: 'd'
         field_5: 'e'
         field_6: 'f' ...