Extracting non zero values from structure variable

조회 수: 21 (최근 30일)
chandra Naik
chandra Naik 2021년 10월 26일
댓글: Stephen23 2021년 10월 26일
Suppose S is a structre variable with following zero and non-zero values , Then How do we extract only non-zero values from structure variable S.
s=100;
for i=1:s
if (sensorCover(i))
S(i).E=0.5;
S(i).xd=xf(i)
S(i).yd=yf(i)
S(i).ir=ircount(i)
S(i).cr=cf(i)
else
S(i).E=0;
S(i).xd=0;
S(i).yd=0;
S(i).ir=0;
S(i).cr=0;
end
end
  댓글 수: 2
KSSV
KSSV 2021년 10월 26일
Question is not clear......what is sensorCover here?
chandra Naik
chandra Naik 2021년 10월 26일
SensorCover(i)---Please assume it as any test condition. Thank you

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

채택된 답변

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 10월 26일
편집: Sulaymon Eshkabilov 2021년 10월 26일
Use logical indexing to take out non-zero values from a sturcture array, e.g.:
S.m(1) =0.1; S.m(2:5)=0; S.m(6:9)=pi; S.k(1:3)=0; S.k(4:5)=-1;
S.m(S.m~=0) % Non-zero values
ans = 1×5
0.1000 3.1416 3.1416 3.1416 3.1416
S.k(S.k~=0) % Non-zero values
ans = 1×2
-1 -1
  댓글 수: 3
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 10월 26일
Most welcome!
Stephen23
Stephen23 2021년 10월 26일
It is simpler to use NONZEROS:
S.m(1) = 0.1;
S.m(2:5) = 0;
S.m(6:9) = pi;
S.k(1:3) = 0;
S.k(4:5) = -1;
nonzeros(S.m)
ans = 5×1
0.1000 3.1416 3.1416 3.1416 3.1416
nonzeros(S.k)
ans = 2×1
-1 -1
Note that the original question showed a non-scalar structure with fields of scalar numerics, whereas the answer given above shows a scalar structure with fields of numeric vectors. These are clearly not the same thing.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by