How to avoid omitting empty items while extracting part of a structure as an array?

4 ビュー (過去 30 日間)
For example, I have a structure
s = struct;
s(1).x = 1;
s(1).name = 'John';
s(2).name = 'Sarah'; % Sarah has no x values because of some unnoticed bug
s(3).x = 3;
s(3).name = 'Robert';
I would like know who is corresponding to "x = 3", so I tried:
1 3
answer = s([s.x].' == 3 ).name % The correct answer should be Robert
answer = 'Sarah'
The reason is that s(2).x was omitted when converting field x into an array.
Is there any way to avoid this dangerous situation?
  2 件のコメント
zhehao.nkd 2023 年 1 月 8 日
Thank you very much! Converting empty values into NaN is the key to the solution of this problem.



Cameron 2023 年 1 月 6 日
Here's one way to do it. The problem is that it will be very hard to get Sarah out of this.
for cc = 1:length(s)
if isempty(s(cc).x)
s(cc).x = NaN;
s([s.x].' == 3 ).name
another similar way is
cc = cellfun(@isempty,{s.x});
s(cc).x = NaN;
s([s.x].' == 3 ).name

その他の回答 (0 件)


Find more on Structures in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by