help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to extract all variables from a structure


From: Andy Buckle
Subject: Re: How to extract all variables from a structure
Date: Fri, 29 Mar 2013 09:54:12 +0000




On 29 March 2013 02:05, Terry Duell <address@hidden> wrote:
On Thu, 28 Mar 2013 21:34:46 +1100, Andy Buckle <address@hidden> wrote:

On 28 March 2013 09:36, Terry Duell <address@hidden> wrote:


I see that I can use the function "getfield" to extract the structure
"data" from the structure "s".
Is there a neat way of extracting all the variables from "data", (ie. so
that they are simply unstructured variables) without having to separately
reference each?

Cheers,


I don't think it is possible. The best you can do is use fieldnames, and
then go through them using getfield. If it's nested and you can't make
assumptions about how it's nested, then make it recursive.


I'm not getting anywhere useful with this.
I can extract the inner structure, and get the fieldnames, as follows...

octave:2> s

s =

  scalar structure containing the fields:

    data ="">
      scalar structure containing the fields:

        a =  7040
        b =  237.60
        c =  244.20
        d =  150
        e =  3000
        f =  14.500
        g =  14.500
        h =  14.500


octave:3> data = ""> octave:4> data

data ="">
  scalar structure containing the fields:

    a =  7040
    b =  237.60
    c =  244.20
    d =  150
    e =  3000
    f =  14.500
    g =  14.500
    h =  14.500

octave:5> list = fieldnames(data);
octave:6> list
list =
{
  [1,1] = a
  [2,1] = b
  [3,1] = c
  [4,1] = d
  [5,1] = e
  [6,1] = f
  [7,1] = g
  [8,1] = h
}
octave:7> newlist = cell2mat(list)
newlist =

a
b
c
d
e
f
g
h

...but get myself all tangled up when I try to use the fieldnames (list, or newlist) with the function "getfield" to extract all the fields from "data".
Can someone please give me a clue as to how I should tackle that?

This might be modified to do something useful. Not sure I understand the problem.
call it with
structprint(s)
and get
[data]
    [w1]
        s =  237.60
    [w2]
        s =  44.200
    [w3]
        s =  150
    [w4]
        s =  3000
    [r1]
        s =  14.500
    [r2]
        s =  14.500
-----------------------------
function structprint (s,depth)
  if 1==nargin
    depth=0;
  end
  if isstruct(s)
    fnames=fieldnames(s);
    for i=1:length(fnames)
      printf("%s[%s]\n",repmat('  ',1,depth*2),fnames{i});
      structprint(getfield(s,fnames{i}),depth+1);
    end
  else
    printf("%s",repmat('  ',1,depth*2));
    s
  end
end
-----------------------------

--
/* andy buckle */

reply via email to

[Prev in Thread] Current Thread [Next in Thread]