newuser
newuser

Reputation: 113

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.

Upvotes: 1

Views: 550

Answers (2)

Divakar
Divakar

Reputation: 221644

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' ...

Upvotes: 1

rayryeng
rayryeng

Reputation: 104545

One would think that you could simply reverse the second and third parameters in the setfield function, but numeric fields are not supported for structs in Octave / MATLAB. What you could possibly do is use num2str to transform each number into a string. You can then use this field to access in your struct. In other words, try this:

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

Now, to access your fields, you would simply call getfield:

val = getfield(hash_reverse, num2str(num));

num is the number you want to use. For example, if we wanted the value using the field of 3:

val = getfield(hash_reverse, num2str(3));
%// or 
%// val = getfield(hash_reverse, "3");

This is what I get:

val = 

c

Upvotes: 1

Related Questions