How do I remove all fields of a structure that have at least one NaN?
Show older comments
I have a structure S with n fields, field1, field2 etc.. How do I remove those fields that have at least one NaN?
Thank you
Accepted Answer
More Answers (2)
Try rmfield
a = [1 nan 3];
bb = [1 2 3];
S.a = a;
S.bb = bb;
S
nms = fieldnames(S);
for i = 1:length(nms)
f = getfield(S,nms{i});
if isnan(sum(f))
S = rmfield(S,nms{i});
end
end
S
5 Comments
James Tursa
on 1 Apr 2020
To generalize this, you can loop over the result of the fieldnames( ) function.
darova
on 1 Apr 2020
Agree. Changed that
Giovanni Barbarossa
on 1 Apr 2020
Edited: Giovanni Barbarossa
on 1 Apr 2020
darova
on 1 Apr 2020
- I would have expected a simpler solution
Im a simple man
- Also something like a combination of isnan and any.
As you wish
if any(isnan(f))
James Tursa
on 1 Apr 2020
Edited: James Tursa
on 1 Apr 2020
@Giovanni: For the invalid variable type, you can test for numeric. E.g.,
if isnumeric(f) && any(isnan(f(:)))
Image Analyst
on 1 Apr 2020
Edited: Image Analyst
on 1 Apr 2020
If you want, you can try to use structfun() but it's rather cryptic. darova's solution is much more intuitive and readable.
By the way, I'd have used any() instead of sum(), k instead of i (since i is the imaginary variable), and dynamic field names:
S.a = [1, nan, 3];
S.bb = [1, 2, 3];
S
nms = fieldnames(S);
for k = 1:length(nms)
thisField = S.(nms{k});
if any(isnan(thisField))
S = rmfield(S, nms{k});
end
end
S
2 Comments
darova
on 1 Apr 2020
thanks bro, appreciate your support
James Tursa
on 1 Apr 2020
Including the the type check here as well:
if isnumeric(thisField) && any(isnan(thisField(:)))
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!