How to check the existance of a struct field at a given index?

p(1).name = 'name1'; p(1).value = 1:10; p(2).name = 'name2';
I want to check existance of p(2).value, but exist and empty is not working for me. How to do?

3 Kommentare

empty(p(2).value) Undefined function 'empty' for input arguments of type 'double'
exist('p(2).name')
ans =
0
Stephen23
Stephen23 am 16 Okt. 2018
Bearbeitet: Stephen23 am 16 Okt. 2018
"I want to check existance of p(2).value, but exist and empty is not working for me. How to do?"
Every element of a structure array has the same fields. So if you have defined this:
p(1).name = 'name1';
p(1).value = 1:10;
p(2).name = 'name2';
Then by definition of a non-scalar structure the field p(2).value also exists. If you have not allocated it a value, then it will be initialized to the empty array. This means it is not clear what your question relates to:
  • p(2).value exists because it was created as soon as you created p(1).value. So testing for its existence is entirely superfluous.
  • The value of that field is []. Is that what you want to test for?
Note that exist is totally irrelevant to this problem.
empty is not a suitable MATLAB function: did you mean isempty ?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

madhan ravi
madhan ravi am 16 Okt. 2018

0 Stimmen

5 Kommentare

I think, this cannot help to me, because I dond wnat to check the hole filed, just the existance of the value of thet filed at a given index, as in the example above!
I want to check p(2).value, and not p.value!
p(1).name = 'name1';
p(1).value = 1:10;
p(2).name = 'name2';
~isempty(p(2).value)
Important: as hinted by madhan's answer, the function used to test for emptiness is isempty, not empty (a completely different function that only works for classes). So instead of
empty(p(2).value)
use
isempty(p(2).value)
Thank you Guillaume

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Gefragt:

am 16 Okt. 2018

Kommentiert:

am 16 Okt. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by