Extract first and last nonzero elemenents inside subarrays avoiding mat2cell

1 次查看(过去 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