2014-09-05 35 views
1

逆向结构我实现这样在八度的结构体:在八度

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 

这是等形式的一个HashMap:{ 'A':1, 'B':2 ....}

我想这个结构形式的反向形式:{1:“A”,2:“b” .....}

编辑:我试图扭转,但渐渐的错误,因为Divakar先生在回答中指出,键不能是结构体中的整数。

在此先感谢。

+1

和...你尝试过什么?你发现了什么问题? – 2014-09-05 14:38:22

+0

为什么不使用数组? – robbrit 2014-09-05 14:38:44

+0

我在将int值映射到char时遇到问题。任何解决方案 – newuser 2014-09-05 14:46:54

回答

1

变量名称或结构字段名称不能以数字开头。如果您遇到任何错误,可能是因为这个原因。因此,为避免此问题,请使用常用关键字并在其后附加数字。

如果你喜欢一个无环路的方法 -

%// 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) 

输出 -

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

问题是,我需要在函数中使用整数键,因为我使用getfield(hash,code),其中code是一个从1开始的整数。 – newuser 2014-09-05 15:24:10

+0

@newuser试试这个 - getfield(hash,strcat(keyword,num2str (code)))' – Divakar 2014-09-05 15:33:13

+0

是的。有效!非常感谢!我也想添加一个空格字符。如:field_27:''。我应该如何添加它? – newuser 2014-09-05 15:43:38

1

人们会认为你可以简单地颠倒setfield函数中的第二个和第三个参数,但Octave/MATLAB中的structs不支持数值字段。你可能做的是使用num2str将每个数字转换为一个字符串。然后你可以使用这个字段来访问你的结构。换句话说,试试这个:

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

现在,访问您的领域,你只需拨打getfield

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

num是您要使用的号码。例如,如果我们想使用3字段中的值:

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

这就是我得到:

val = 

c