How to select or group sections of an array without using indexing

조회 수: 1 (최근 30일)
Femi Bolarinwa
Femi Bolarinwa 2020년 10월 19일
댓글: Stephen23 2020년 10월 20일
So i have an array of elements like this:
A = [NaN; NaN; NaN; NaN; 2; 3; 6; 7; NaN; NaN; NaN; NaN; NaN; 4; 6; 8; 8; NaN; NaN; NaN; NaN]
What I need is to collect each group of numbers into new separate arrays like this:
B = [2; 3; 6; 7]
C = [4; 6; 8; 8]
How do i do that without hard-coding with the array index numbers? Thanks

채택된 답변

Stephen23
Stephen23 2020년 10월 20일
>> A = [NaN, NaN, NaN, NaN, 2, 3, 6, 7, NaN, NaN, NaN, NaN, NaN, 4, 6, 8, 8, NaN, NaN, NaN, NaN];
>> X = diff([true,isnan(A),true]);
>> B = find(X<0);
>> E = find(X>0)-1;
>> F = @(b,e) A(b:e);
>> C = arrayfun(F,B,E,'uni',0);
>> C{1}
ans =
2 3 6 7
>> C{2}
ans =
4 6 8 8
  댓글 수: 2
Femi Bolarinwa
Femi Bolarinwa 2020년 10월 20일
What if A was a column vector instead:
A = [NaN; NaN; NaN; NaN; 2; 3; 6; 7; NaN; NaN; NaN; NaN; NaN; 4; 6; 8; 8; NaN; NaN; NaN; NaN];
How would this change the code to achieve:
C = [2; 3; 6; 7]
B = [4; 6; 8; 8]
Thanks!
Stephen23
Stephen23 2020년 10월 20일
X = diff([true;isnan(A(:));true]); % works for either column or row vector A

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by