help-octave
[Top][All Lists]

## Re: Structures

 From: Jaroslav Hajek Subject: Re: Structures Date: Thu, 11 Feb 2010 08:00:11 +0100

```On Thu, Feb 11, 2010 at 4:48 AM, Mike B. <address@hidden> wrote:
> Hi All,
>
> Would appreciate advice how to the following efficiently:
> I have two structures A and B.
> 1. Need to cycle over the fields of A in a particular order.
> 2. If B has a field with an identical name then A is assigned the content of
> B's field.
> 3. Evaluate the field in A.
>
> For example (f1 then f2 then f3):
> A.f1 = 1
> A.f2 = A.f1 * 2
> A.f3 = "abc"
>
> B.f2 = A.f1 *5
> B.f3 = "def"
>
> so after looping over A (and given B) the output is
> A.f1 = 1
> A.f2 = 5
> A.f3 = "def"
>
>
> Cheers,
> Mike.
>
>

One good option is to use the string dictionary class from the general package:

octave:1> A.f1 = 1
A =
{
f1 =  1
}

octave:2> A.f2 = A.f1 * 2
A =
{
f1 =  1
f2 =  2
}

octave:3> A.f3 = "abc"
A =
{
f1 =  1
f2 =  2
f3 = abc
}

octave:4>
octave:4> B.f2 = A.f1 *5
B =
{
f2 =  5
}

octave:5> B.f3 = "def"
B =
{
f2 =  5
f3 = def
}

octave:6> A = dict (A)
A =

dict: {
f1 :  1
f2 :  2
f3 : abc
}
octave:7> B = dict (B)
B =

dict: {
f2 :  5
f3 : def
}
octave:8> C = join (A, B)
C =

dict: {
f1 :  1
f2 :  5
f3 : def
}

To access the merged values in a particular order:

octave:9> values = C({"f2", "f1", "f3", "f1"})
values =

{
[1,1] =  5
[1,2] =  1
[1,3] = def
[1,4] =  1
}

To convert the dictionary back to a struct:

octave:10> struct (C)
ans =
{
f1 =  1
f2 =  5
f3 = def
}

hth

--
RNDr. Jaroslav Hajek, PhD
computing expert & GNU Octave developer
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz

```