Nicolas T.
Nicolas T.

Reputation: 3

get fieldname of a data struct matlab

I have the following nested struct:

hole 1x200 struct, diam 1x12 struct, which has the following fields: pos, freq1, fre12

That is:

hole(1 to 200).diam(1 to 12).pos
                            .freq1
                            .freq2

From a value (freq1 and freq2), I would like to obtain the field name of the struct. So I will need to find the value that matches with freq1 and freq2 and show the fieldname.

I tried to use structfun in order to apply a function to each field.

[struct.field]=structfun(@(x) find(x.freq1==27.059783995484867 & freq2==76.468355874897000))

But I guess I am writing something wrong on the code.

Also I create an anonymous fuction but I have the following error:

'Error using structfun / Inputs to STRUCTFUN must be scalar structures'

. How ever when I verified if an specific value of the struct is scalar, I have a positive answerd: isscalar(hole(130).diam(10))

I belive I more near the solution using this script:

myfun=@(yourarray,desiredvalue) yourarray==desiredvalue;
%//Apply function to each field of scalar structure, it SCALAR??
desiredfieldindex=myfun(structfun(@(x) x,hole),26.697046257785030) 
desiredFieldName=fNames(desiredFieldIndex)

I don´t know if I am in the rigth path, or I should utilize the function find. ALso I that case I don´t know how to implement it.

Upvotes: 0

Views: 379

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

Couple of things.

  1. FLOATING POINT VALUES! Careful!! Never compare a floating point value as val==0.3! do abs(val-0.3)<10^-8 or something similar. Read more here.

  2. You are using structfun wrong. The function needs 2 arguments, and you are just passing 1! However, structfun will apply a function to each field so you are not using it rigth either in that sense. Lets see an example

example:

a.hithere=5;
a.notthis=3;
fun=@(x)x==5;
[isfive]=structfun(fun,a)


isfive =

     1
     0

As you can see, it applies the function to each of them. If you try to change the function to fun=@(x)x.hithere==5 you will get an error! As the function is applied to each field, and x.hithere.hithere or x.notthis.hithere do not exist.

If you want to check both values, you will need to check them independently making two separated calls to structfun or avoiding structfun and just making a for loop.

Upvotes: 1

Related Questions