Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how in matlab check for existence of a structure with fields in the workspace

I have a string and want to check if in the workspace exist any variable with the same name. In the workspace I have also many structures M.N.O M.N.N M.N.M etc. I can only check if there exist a variable with the name M. How to go deeper into this structure? I tried:

exist('M.N')
YesNo = any(strcmp(who,'M.N.O'))
evalin('base','exist(''M.N.O'',''var'')')

all give me the same problem so I am stuck.

like image 717
beginh Avatar asked Aug 20 '12 16:08

beginh


People also ask

How do you check if a field exists in a structure MATLAB?

1. To determine if a field exists in a particular substructure, use 'isfield' on that substructure instead of the top level. In the example, the value of a.b is itself a structure, and you can call 'isfield' on it. Note: If the first input argument is not a structure array, then 'isfield' returns 0 (false).

How do I see the structure of a structure in MATLAB?

Structures store data in containers called fields, which you can then access by the names you specify. Use dot notation to create, assign, and access data in structure fields. If the value stored in a field is an array, then you can use array indexing to access elements of the array.

How do you pull a field out of a structure in MATLAB?

s = rmfield( s , field ) removes the specified field or fields from structure array s .

What is a field in a structure MATLAB?

Arrays with named fields that can contain data of varying types and sizes. A structure array is a data type that groups related data using data containers called fields. Each field can contain any type of data. Access data in a structure using dot notation of the form structName. fieldName .


2 Answers

You can use isfield to check if a variable has a specific field. See the link for examples!

For your example, you'd need:

isfield(M,'N')

and if true, you can go deeper:

isfield(M.N,'O')

Notice that

isfield(M,'N.O')

won't work ;)

like image 169
Gunther Struyf Avatar answered Nov 01 '22 05:11

Gunther Struyf


One option: write a recursive function to expand structures down to their leaf fields, appending the fields to a list.

(untested, conceptual code - probably won't work quite right as is)

function varlist = getStructFields(var,varlist)
if isstruct(var)
    fn = fieldnames(var);
    varlist = vertcat(varlist,fn); %# append fields to the list
    for field = fn' %# ' create row vector; iterate through fields
         varlist = getStructFields(var.(char(field)), varlist); %# recursion here 
    end
end
end

Then you can use the any(strcmp(who,'M.N.O')) check you already came up with.

like image 23
tmpearce Avatar answered Nov 01 '22 07:11

tmpearce