Extract first and last nonzero elemenents inside subarrays avoiding mat2cell
Afficher commentaires plus anciens
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
Plus de réponses (1)
DGM
le 22 Mar 2021
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
1 commentaire
Santos García Rosado
le 22 Mar 2021
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!