MATLAB: Search within a structure using a string

evalstructures

Hello Im trying to check if a string exist within a strucure:
The string is the structure path, which I created using sprintf I can not detect if the string coincide with the path of an existent structure in the workspace (Clicks).
Eval dosent work for structures neither fieldnames … there is any way to check if exist or not in the workspace???
thanks in advance
prof_l=unique(prof_list);
shore_l=unique(shore_list);
% read clicks and extract shoreline
met=('fix');
%
for i1=1:numel(prof_l)
p=prof_l(i1,1);
for i2=1:1:numel(shore_l)
s=shore_l(i2,1);
file=(sprintf('Clicks.prof_%u.shore_%u.%s',p,s,met));
if exist(eval(file),var) ==1;
disp('hola')
end
end
end

Best Answer

Here is the test you asked for. I would point out that if the answer is True, that the structure exists, chances are high that you are planning to use eval() to get at the value stored, and that you should be strongly avoiding doing that.
function tf = struct_exists(candidate)
%Written 20150905 - Walter Roberson
%{
Here is a structure exist. In this version it *only* handles flat structures, no
indexing, no dynamic fieldnames.
The empty string and [] are accepted as valid arguments (and return false). Other
non-string arguments will generate a warning (and false)
The last field given is _not_ tested to see if it is a structure (only whether it
exists) so that this routine can be used to test whether a field exists. As a design
decision this extends to the case where the passed name has no subfields given and
so is the last field name given: in this case true is returned if the name exists
whether or not the name is a structure.
The use of warnings instead of error was a design decision, one that is most
debatable for the case of invalid input. I used warnings because this is
supposed to be an existence test, and if the answer is "No that is not a valid
arrangement of structure references" then Okay, that's why you *tested* rather
than just went ahead and used the string.
%}
tf = false;
if ~( ischar(candidate) || (isdouble(candidate) && isempty(candidate)) )
warning('struct_exist: only character strings or [] permitted as argument')
return
end
if isempty(candidate); return; end
if regexp(candidate, '[^a-zA-z0-9_.]')
warning('struct_exist: only fieldnames and ''.'' permitted');
return;
end
parts = regexp(candidate, '\.', 'split');
if ~ evalin('caller', sprintf('exist(''%s'', ''var'')', parts{1}));
warning( sprintf('struct_exist, "%s" is not a variable', parts{1}) );
return;
end
for K = 1 : length(parts) - 1
subname = strjoin(parts(1:K), '.');
try
fn = evalin('caller', sprintf('fieldnames(%s)', subname));
catch ME
%some leading fieldname was not a structure
fn = {};
end
if ~ismember(parts{K+1}, fn)
%some leading prefix does not have the next part as a field
% no warning because this is a normal use case
return
end
end
tf = true;
end