Extract first and last nonzero elemenents inside subarrays avoiding mat2cell

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

 Réponse acceptée

Bruno Luong
Bruno Luong le 22 Mar 2021
Modifié(e) : Bruno Luong le 22 Mar 2021
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))).'

Plus de réponses (1)

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

Catégories

Produits

Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by