显示没有混乱的结构字段

Ric*_*ard 11 octave

我在Octave中有一个包含一些大数组的结构.

我想知道这个结构中字段的名称,而不必查看所有这些大数组.

例如,如果我有:

x.a=1;
x.b=rand(3);
x.c=1;
Run Code Online (Sandbox Code Playgroud)

采取结构的明显方法如下:

octave:12> x
x =

  scalar structure containing the fields:

    a =  1
    b =

       0.7195967   0.9026158   0.8946427   
       0.4647287   0.9561791   0.5932929   
       0.3013618   0.2243270   0.5308220   

    c =  1
Run Code Online (Sandbox Code Playgroud)

在Matlab中,这看起来更简洁:

 >> x
 x = 
    a: 1
    b: [3x3 double]
    c: 1
Run Code Online (Sandbox Code Playgroud)

如何在不看到所有这些大数组的情况下查看字段/字段名称?

有没有办法在Octave中显示简洁的概述(如Matlab的)?

谢谢!

slm*_*slm 13

您可能需要查看基本用法和示例.提到的几个功能听起来像是控制终端中的显示.

  • struct_levels_to_print
  • print_struct_array_contents

这两个功能听起来像是你想做的.我试过了两个,无法让第二个工作.第一个功能改变了终端输出,如下所示:

octave:1> x.a=1;
octave:2> x.b=rand(3);
octave:3> x.c=1;
octave:4> struct_levels_to_print
ans =  2
octave:5> x
x =
{
  a =  1
  b =

     0.153420   0.587895   0.290646
     0.050167   0.381663   0.330054
     0.026161   0.036876   0.818034

  c =  1
}

octave:6> struct_levels_to_print(0)
octave:7> x
x =
{
  1x1 struct array containing the fields:

    a: 1x1 scalar
    b: 3x3 matrix
    c: 1x1 scalar
}
Run Code Online (Sandbox Code Playgroud)

我正在运行旧版Octave.

octave:8> version
ans = 3.2.4
Run Code Online (Sandbox Code Playgroud)

如果我有机会,我会检查其他功能,print_struct_array_contents看看它是否符合您的要求.Octave 3.6.2 看起来是截至2012年11月的最新版本.


car*_*aug 5

使用 fieldnames ()

octave:33> x.a = 1;
octave:34> x.b = rand(3);
octave:35> x.c = 1;
octave:36> fieldnames (x)
ans = 
{
  [1,1] = a
  [2,1] = b
  [3,1] = c
}
Run Code Online (Sandbox Code Playgroud)

或者,您希望它是递归的,请将以下内容添加到.octaverc文件中(您可能希望根据自己的喜好进行调整)

function displayfields (x, indent = "")
  if (isempty (indent))
    printf ("%s: ", inputname (1))
  endif
  if (isstruct (x))
    printf ("structure containing the fields:\n");
    indent = [indent "  "];
    nn = fieldnames (x);
    for ii = 1:numel(nn)
      if (isstruct (x.(nn{ii})))
        printf ("%s %s: ", indent, nn{ii});
        displayfields (x.(nn{ii}), indent)
      else
        printf ("%s %s\n", indent, nn{ii})
      endif
    endfor
  else
    display ("not a structure");
  endif
endfunction
Run Code Online (Sandbox Code Playgroud)

然后可以通过以下方式使用它:

octave> x.a=1;
octave> x.b=rand(3);
octave> x.c.stuff = {2, 3, 45};
octave> x.c.stuff2 = {"some", "other"};
octave> x.d=1;
octave> displayfields (x)
x: structure containing the fields:
   a
   b
   c: structure containing the fields:
     stuff
     stuff2
   d
Run Code Online (Sandbox Code Playgroud)