MATLAB Answers

How to check if a element of a struct is empty?

10 views (last 30 days)
Benson Gou
Benson Gou on 14 Oct 2020
Commented: Ameer Hamza on 15 Oct 2020
Dear All,
I defined a struct and initialize it in the following way.
Res_All_Meas = struct([]);
[Res_All_Meas(1000).ind] = 0;
[Res_All_Meas(1000).res] = 0;
[Res_All_Meas(1000).xline] = 0;
[Res_All_Meas(1000).colnum] = 0;
Now in an iteration, I want to check if Res_All_Meas(i) is empty or not. If it is empty, I will assign some valeus to it.
Thanks a lot.
Benson

  3 Comments

Stephen Cobeldick
Stephen Cobeldick on 14 Oct 2020
"I defined a struct and initialize it in the following way."
Res_All_Meas = struct([]);
[Res_All_Meas(1000).ind] = 0;
[Res_All_Meas(1000).res] = 0;
[Res_All_Meas(1000).xline] = 0;
[Res_All_Meas(1000).colnum] = 0;
The indexing into Res_All_Meas(1000) refers to one single element of Res_All_Meas, so the square brackets are not required.
"I want to check if Res_All_Meas(i) is empty or not."
By definition one element of an array (which includes numeric, char, cell, and structure) has size 1x1(x1x1x1...) and so cannot be empty, one element is always scalar.
Do you really want to check if the field contents are empty?
Benson Gou
Benson Gou on 14 Oct 2020
Yes, I want to check if the field contents are empty. The field contents for Res_All_Meas(i) are zero before Res_all_Meas(i) is assigned a value. But how?
Thanks.
Beneon
Stephen Cobeldick
Stephen Cobeldick on 15 Oct 2020
"I want to check if the field contents are empty."
See my answer.
"The field contents for Res_All_Meas(i) are zero before Res_all_Meas(i) is assigned a value."
Not in your example. What you showed has all fields of every structure element Res_All_Meas(1:999) containing empty numeric arrays, and the last element Res_All_Meas(1000) for which each field contains 0.

Sign in to comment.

Answers (2)

Ameer Hamza
Ameer Hamza on 14 Oct 2020

  2 Comments

Benson Gou
Benson Gou on 14 Oct 2020
I used isempty and tried several ways, but does not work. I think the isempty() works for number arrays.
Thanks a lot.
Benson
Ameer Hamza
Ameer Hamza on 15 Oct 2020
You need to apply isempty on a particular field of a struct. Something like this
tf = ismpty(Res_All_Meas(1).ind)

Sign in to comment.


Stephen Cobeldick
Stephen Cobeldick on 15 Oct 2020
Edited: Stephen Cobeldick on 15 Oct 2020
fun = @(s) all(structfun(@isempty,s)); % check the fields of a scalar structure.
idx = arrayfun(fun,Res_All_Meas); % indices of those structure elements with ALL fields empty.

  0 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!