How to check if there is any field in structure?

292 ビュー (過去 30 日間)
Najmeh Eskandari
Najmeh Eskandari 2019 年 2 月 11 日
コメント済み: Nicholas Ayres 2021 年 4 月 6 日
Hi.
I have a structures with no field and want to check is there any field in it or no?
L1=struct();
isempty L1
the result is 0.I know that L1 is a struct with no field(not empty).
so i use:
L1=struct([])
but in this case the result is 0 too.
How can check is there any fields in an empty structure?
  1 件のコメント
Nicholas Ayres
Nicholas Ayres 2021 年 4 月 6 日
A misunderstanding of using functions in MatLab is shown in this question.
Read the next section of this comment if you don't see the issue.
When you put a space after a function name, matlab interprets the space-separated terms as char[] inputs to the function.
So these two function calls are synonymous:
isempty L1
isempty('L1')
and are NOT the same as:
isempty(L1)
which was intended. BE CAREFUL OF THIS!!
However the approach taken would still not produce the desired output (read the next section to find out why).
WHY the approach taken in the question would not work (even if done correctly).
However, assuming that this term HAD been written correctly, isempty(L1), this would still NOT have produced the desired result as "isempty" tests the dimensions of the struct array and NOT the number of fields that the contained structs have.
So:
L1 = struct();
isempty(L1) % = FALSE because the struct command produces a 1x1 struct array.
L1 = struct([]);
isempty(L1) % = TRUE because the struct command now produces a 0x0 struct array and NOT because of the number of fields.
If we were to do:
L1 = struct('hi',10);
L1(1) = [];
isempty(L1)
we would get TRUE because L1 is now a 1x0, but the struct still HAS the field "hi".
The answer
From my understanding, the only solution is that provided by the accepted answer. Collect the fieldnames of the struct and test if THAT is empty.
isempty(fieldnames(L1))
This is as the the "fieldnames" will create a vector cell array of the fieldnames (as char[]), thus the first dimension is the same as the number of fieldnames and a 0x1 cell array IS empty.

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

採用された回答

KSSV
KSSV 2019 年 2 月 11 日
isempty(fieldnames(L1))

その他の回答 (1 件)

Yeqing Wang
Yeqing Wang 2020 年 1 月 26 日
isempty(L1)

カテゴリ

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