Extract first and last nonzero elemenents inside subarrays avoiding mat2cell

조회 수: 2 (최근 30일)
Can somone please give me a hand?
I have a matrix A such as:
A = [0 0 1 2 0 5 0 0 6 0 3 0 ; 0 3 0 2 6 0 0 0 0 0 0 0];
I'd like to check where are the first and last nonzero values along my subarrays of 6 elements on each row. So the expected Output shoul be:
Out = [0 0 1 0 0 1 0 0 1 0 1 0 ; 0 1 0 0 1 0 0 0 0 0 0 0];
I know I can easilly use mat2cell to perform this but I'd like to avoid using this funciton.
Thank's for the help,
Santos

채택된 답변

Bruno Luong
Bruno Luong 2021년 3월 22일
편집: Bruno Luong 2021년 3월 22일
A = [0 0 1 2 0 5 0 0 6 0 3 0 ; 0 3 0 2 6 0 0 0 0 0 0 0];
b = reshape(A.',6,[]) ~= 0;
[m,n] = size(b);
[~,istart] = max(b,[],1);
[~,istop] = max(flip(b,1),[],1);
i = [istart; m+1-istop] + (0:n-1)*m;
B = zeros(size(b));
B(i) = b(i);
Out = reshape(B,flip(size(A))).'

추가 답변 (1개)

DGM
DGM 2021년 3월 22일
I arbitrarily chose to avoid loops and find() and ended up with this ugly thing. It works, but I wouldn't call it elegant. I added some dummy values to the test array to demonstrate that it handles cases where there are no matches
A = [0 0 1 2 0 5 0 0 6 0 3 0 ; 0 0 0 0 0 0 0 0 0 0 0 0; 0 3 0 2 6 0 0 0 0 0 0 0];
A=reshape(A',6,[])'
matches=[sum(cumprod(A == 0,2),2)+1; 6-sum(cumprod(A == 0,2,'reverse'),2)];
matches=[[1:6 1:6]; matches']';
matches=matches(matches(:,2)>0 & matches(:,2)<7,:);
B=zeros(size(A));
B(sub2ind(size(A),matches(:,1),matches(:,2)))=1;
B=reshape(B',12,[])'
this yields:
B =
0 0 1 0 0 1 0 0 1 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 1 0 0 0 0 0 0 0
Again, I added the extra row

카테고리

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

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by