how to search values?

48 views (last 30 days)
Dimitrios
Dimitrios on 26 Sep 2014
Answered: Guillaume on 26 Sep 2014
I was wondering if there is a way to find if any value of all my variables have a specific value e.g. NaN or Inf.Using OOP technics, workspace dont show all the variables,so i have to search manually all the variables in all classes to check it. Thanks in advance
  2 Comments
Dimitrios
Dimitrios on 26 Sep 2014
Yea.Sorry i wasnt so precise. What i am trying to say is: with Cntrl+f user can search for a word in a .m file, Cntrl+Shift+F the same for multiple files. So i was wondering if there something in graphical interfece that can search values outputed from an allready run code.I dont want to extract something.I just want to check if any values of my variables are inf or NaN.I believe there is not but worth to ask. On the other hand, a function that search all my variables to check the desirable condition doesnt worth as i hae to write all the variables. Thanks anyway for your time.

Sign in to comment.

Answers (2)

Andrew Reibold
Andrew Reibold on 26 Sep 2014
Edited: Andrew Reibold on 26 Sep 2014
To list all variables in your workspace
variables = who;
With this, you can loop through every variable, and check if it has a nan value
for i = 1:length(variables)
...
%check for inf and nan and whatever else you want
...
end
. FYI - If you didn't know, you can use eval('string') to check the values of the strings of variable names .
Here is an example of one way to check for infs and nans. I'm not sure how exactly you want to do it. I hope this helps!
MyArray = [ 0 1 4 3 nan 3 4 nan 3 inf ];
find(isnan(MyArray))
ans =
5 8
find(isinf(MyArray))
ans=
10

Guillaume
Guillaume on 26 Sep 2014
To check if any of the values of cell arrays, structures or objects are NaN or Inf, you would have to write a function that inspect the cell array elements / structure fields / object properties, and call itself again if any of them is itself a cell array / structure / object.
Something like this (untested, there may be errors):
function [tf, names] = isnanobject(o)
names = {};
if isnumeric(o) || ischar(o)
tf = any(isnan(o));
elseif iscell(o)
tf = any(cellfun(@isnan, o(:)));
elseif isstruct(o)
tf = false;
for se = 1:numel(o) %in case o is an array of structure
for fn = fieldnames(o)'
[tff, namef] = isnanobject(o(se).(fn))
if tff
tf = true;
names = [names, sprintf('(%d).%s%s', se, fn, namef)];
end
end
end
elseif isobject(o)
tf = false;
for so = 1:numel(o) %in case o is an array of objects
for pn = properties(o)'
[tff, namep] = isnanobject(o(se).(pn))
if tff
tf = true;
names = [names, sprintf('(%d).%s%s', se, fn, namep)];
end
end
end
else %neither numeric, char, cell, struct, or object
error('forgot something');
end
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by