Check if any field in a given structure is empty

235 ビュー (過去 30 日間)
ihrram
ihrram 2017 年 3 月 6 日
コメント済み: Dominique 2022 年 2 月 16 日
Hello everyone,
I have a structure with quite some fields and I want to check, if any of the fields are empty. Is there a way to do this without checking for each field individually?
Currently I have an if statement with many ORs to do this:
if isempty(structure.field1) || isempty(structure.field2)
and so on
I tried to do the same with
any(isempty(fieldnames(structure))
but obviously the fieldnames are not empty.

採用された回答

Walter Roberson
Walter Roberson 2017 年 3 月 6 日
any( structfun(@isempty, YourStructure) )
  5 件のコメント
Gabor
Gabor 2019 年 3 月 5 日
It dis not for me on a table:
a.table{1}=table();
a.table{2}=table();
>> any( structfun(@isempty, a.table{20}) )
Index exceeds matrix dimensions.
>> any( structfun(@isempty, a.table{2}) )
Error using structfun
Inputs to STRUCTFUN must be scalar structures.
How can I check if a.table{20} exists or not or empty? Anything that whould give me information of it exsistance? I could not find any function that could have helped so far.
Thank you
Walter Roberson
Walter Roberson 2019 年 3 月 9 日
if length(a.table) >= 20 & ~isempty(a.table{20})

サインインしてコメントする。

その他の回答 (2 件)

Ross Nye
Ross Nye 2017 年 11 月 30 日
I'm going to leave this here in case someone comes across this page looking for a similar answer to what I was.
I have a 1xN struct with many fields. One particular field was supposed to be boolean, but only the falses had been entered and the rest were []. The above answers didn't seem to help me, but I did find something on Reddit which did.
emptyIndex = find(arrayfun(@(MyStruct) isempty(MyStruct.myField),MyStruct));
I can then use emptyIndex to set the fields to true as needed.
HTH someone.
  3 件のコメント
Selene Fregosi
Selene Fregosi 2019 年 8 月 13 日
This helped me too - thank you!
Andres
Andres 2021 年 5 月 27 日
This will work as well
find(cellfun(@isempty,{MyStruct.myField}))
for a struct array MyStruct with field myField.
Note in many cases you don't need find for indexing.
Example: fill empty fields with 0s
MyStruct(3).myField = 123;
hasNone = cellfun(@isempty,{MyStruct.myField});
[MyStruct(hasNone).myField] = deal(0);

サインインしてコメントする。


LeChat
LeChat 2020 年 8 月 13 日
It might be a bit dirty because I use a loop but it works:
ind=[];
for ii=1:numel(MyStruct)
if isempty(MyStruct(ii).FieldName)
ind=[ind, ii];
end
end
Then ind contains all the indexes where the structure field is empty.
For instance if you then want to remove them from the structure:
MyStruct_init=MyStruct;
MyStruct(ind)=[];
Hope this helps!
  1 件のコメント
Dominique
Dominique 2022 年 2 月 16 日
Quick and dirty works :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by