how to search values?
조회 수: 28 (최근 30일)
이전 댓글 표시
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
답변 (2개)
Andrew Reibold
2014년 9월 26일
편집: Andrew Reibold
2014년 9월 26일
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
댓글 수: 0
Guillaume
2014년 9월 26일
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!