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
  1 件のコメント
Santos García Rosado
Santos García Rosado 2021 年 3 月 22 日
Thank you DGM. Check Bruno's answer. You might like the code he came up with.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating 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