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.
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).
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.
s = rmfield( s , field ) removes the specified field or fields from structure array s .
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 .
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 ;)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With