Finding length of a struct, excluding NaN values

조회 수: 4 (최근 30일)
Manny Kins
Manny Kins 2019년 7월 8일
편집: Stephen23 2019년 7월 8일
I have a struct with the following layout:
T X Y
[0,1] [0, 1] [0,5]
[0] [2] [2]
NaN NaN NaN
NaN NaN NaN
NaN NaN NaN
NaN NaN NaN
I want to find the length of the struct excluding the trailing NaN values at the bottom. So in this case the length would be 2 instead of 6.
I have attached a file with some of the values that I am using and the struct shape. Thanks

채택된 답변

Stephen23
Stephen23 2019년 7월 8일
편집: Stephen23 2019년 7월 8일
You can do this very easily with the accepted answer to your very similar question from two months ago:
Just use the logical variable X:
>> F = @(s)all(structfun(@(a)isscalar(a)&&isnan(a),s)); % or ANY
>> X = arrayfun(F,AllData.Passive)
X =
0 0 0 0 1 1 1 1 1 1 1 0 0 0 0
>> nnz(~X)
ans = 8
  댓글 수: 4
Manny Kins
Manny Kins 2019년 7월 8일
Hi Stephen, yes sorry your answer does indeed give the length of a struct without including any NaN values. I was just mentioning that for me when the struct becomes quite large (lengths of around 1000000) the code:
X = arrayfun(F,AllData.Passive)
becomes very slow. I have tried a workaround
if isnan(AllData.Passive(j).PX)
break
end
which just breaks out of the loop when it comes across a NaN value.
This seems to work much faster.
Your suggestion is however much more universal in that it can be applied to structs where there are NaN values scattered around the struct and do not only form below the useful data.
Thanks
Stephen23
Stephen23 2019년 7월 8일
편집: Stephen23 2019년 7월 8일
@Manny Kins: a well-designed loop will most likely be faster than arrayfun.

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by