How do I find out a struct is empty?

155 ビュー (過去 30 日間)
Sean
Sean 2023 年 9 月 27 日
編集済み: Sean 2023 年 9 月 28 日
There are instances in a .mat file where there is information and no information within a particular struct. I'm trying to figure out how to identify that within the struct where there is no furture information avaliable, it's an empty struct.
Let's say a .mat file contains below
A = struct;
A.B = '1';
A.C = '2';
A.D = '3';
but there is another file that contains only what's below
A = struct;
Depending on what which file, or mutiple files that contain various numbers of variables, how do I check if a struct is empty so that I'll be able to initialize the data that is not empty into EditFields of an application.

採用された回答

Voss
Voss 2023 年 9 月 27 日
It looks like you want to find out whether a struct has any fields or not, for which you can use isempty(fieldnames(A))
A = struct;
A.B = '1';
A.C = '2';
A.D = '3';
isempty(fieldnames(A))
ans = logical
0
A = struct;
isempty(fieldnames(A))
ans = logical
1
  2 件のコメント
Voss
Voss 2023 年 9 月 27 日
編集済み: Voss 2023 年 9 月 27 日
Whether the struct is empty is another question, as empty and non-empty struct arrays can have fields or no fields.
A = struct('B',{}); % empty struct array with one field ('B')
is_empty_struct = isempty(A), has_no_fields = isempty(fieldnames(A))
is_empty_struct = logical
1
has_no_fields = logical
0
A = struct('B',{1 2 3}); % non-empty (size 1-by-3) struct array with one field ('B')
is_empty_struct = isempty(A), has_no_fields = isempty(fieldnames(A))
is_empty_struct = logical
0
has_no_fields = logical
0
A = rmfield(A,'B'); % non-empty struct array with no fields
is_empty_struct = isempty(A), has_no_fields = isempty(fieldnames(A))
is_empty_struct = logical
0
has_no_fields = logical
1
A = A([]); % empty struct array with no fields
is_empty_struct = isempty(A), has_no_fields = isempty(fieldnames(A))
is_empty_struct = logical
1
has_no_fields = logical
1
Sean
Sean 2023 年 9 月 28 日
編集済み: Sean 2023 年 9 月 28 日
Thank you for helping me out, I tried to implement it, but I implemented a try catch statement and works.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by