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

조회 수: 1 (최근 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:
disp([s.x].')
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
Askic V
Askic V 2023년 1월 6일
편집: Askic V 2023년 1월 6일
It is because you don't compare the elements in a consistent way. For example,
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';
[s.x].'
ans = 2×1
1 3
so you compare two element vector to a scalar (3).
The best way to avoid these, as you called it dangerous situations, is to make sure you don't have empty elements.
So correct way to implement this would be (one of many ways):
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';
% Find empty elements and replace them with Nan
ind = cellfun(@isempty,{s(:).x});
s(ind).x = NaN;
answer = s([s.x].' == 3 ).name % The correct answer should be Robert
answer = 'Robert'
zhehao.nkd
zhehao.nkd 2023년 1월 8일
Thank you very much! Converting empty values into NaN is the key to the solution of this problem.

댓글을 달려면 로그인하십시오.

채택된 답변

Cameron
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;
end
end
s([s.x].' == 3 ).name
another similar way is
cc = cellfun(@isempty,{s.x});
s(cc).x = NaN;
s([s.x].' == 3 ).name

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by