remove first s and last t rows of a matrix containing NaN, leave lows in the middle containing NaN.
조회 수: 6 (최근 30일)
이전 댓글 표시
I have a Tx2 Matrix A and I would like to remove the rows in the beginning and in the end that contain any NaN. For example:
A=[[NaN;NaN;NaN;4;1;NaN;5;6;8;NaN;NaN],[NaN;NaN;2;7;6;5;NaN;6;18;2;NaN]]
should the equal to:
A=[[4;1;NaN;5;6;8],[7;6;5;NaN;6;18]]
many thanks for your help, Jo.
댓글 수: 0
채택된 답변
Thorsten
2014년 12월 4일
There might be smarter solutions to figure out the indices of leading and trailing 1's in nanflag, but this solution works:
A=[[NaN;NaN;NaN;4;1;NaN;5;6;8;NaN;NaN],[NaN;NaN;2;7;6;5;NaN;6;18;2;NaN]];
nanflag = isnan(sum(A'));
ind = []; for i = 1:numel(nanflag), if nanflag(i) == 1, ind = [ind i]; else break, end, end
for i = numel(nanflag):-1:1, if nanflag(i) == 1, ind = [ind i]; else break, end, end
Anew = A(setdiff(1:size(A,1), ind), :);
추가 답변 (2개)
Guillaume
2014년 12월 4일
A=[[NaN;NaN;NaN;4;1;NaN;5;6;8;NaN;NaN],[NaN;NaN;2;7;6;5;NaN;6;18;2;NaN]];
removestart = logical(sum(cumprod(isnan(A)), 2));
removeend = flipud(logical(sum(cumprod(flipud(isnan(A))), 2)));
A(removestart | removeend, :) = []
댓글 수: 3
Guillaume
2014년 12월 4일
편집: Guillaume
2014년 12월 4일
Works fine on R2014b, which version are you using?
In any case if cumprod does not accept logical, just convert them to double:
A=[[NaN;NaN;NaN;4;1;NaN;5;6;8;NaN;NaN],[NaN;NaN;2;7;6;5;NaN;6;18;2;NaN]];
nanpos = double(isnan(A));
removestart = logical(sum(cumprod(nanpos), 2));
removeend = logical(sum(cumprod(nanpos, 'reverse'), 2));
A(removestart | removeend, :) = []
I've also simplify the calculation of removeend. I didn't realise that cumprod had a reverse option.
Shame you accepted a less efficient code.
C.J. Harris
2014년 12월 4일
Nobody should ever need more than one line:
A = [[NaN;NaN;NaN;4;1;NaN;5;6;8;NaN;NaN],[NaN;NaN;2;7;6;5;NaN;6;18;2;NaN]];
A2 = A(find(~any(isnan(A),2),1,'first'):find(~any(isnan(A),2),1,'last'),:);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!