Find the index of first and last non zero in column

4 ビュー (過去 30 日間)
Teerapong Poltue
Teerapong Poltue 2021 年 6 月 2 日
コメント済み: Chunru 2021 年 6 月 2 日
I got the array as shown
I would like to extract the index (idx) of the first and last non zero in column, how can I do that.
The expected return of the code is
data(idx_first) = [1 1 2]
data(idx_last) = [1 5 5]

採用された回答

Chunru
Chunru 2021 年 6 月 2 日
x = [0 1 0 4; 1 2 0 1; 0 1 2 0; 0 0 0 0]
[m, n] = size(x);
ind = zeros(1, n);
for i=1:n
xlast = find(x(:, i), 1, 'last');
ind(i) = sub2ind([m n], xlast, i);
end
x(ind)
  2 件のコメント
Teerapong Poltue
Teerapong Poltue 2021 年 6 月 2 日
ther's a tiny problem on this code when the colum is entire 0, it caused error in sub2ind. How can I solve that?
Chunru
Chunru 2021 年 6 月 2 日
[m, n] = size(x);
ind = nan(1, n);
for i=1:n
xlast = find(x(:, i), 1, 'last');
if ~isempty(xlast)
ind(i) = sub2ind([m n], xlast, i);
end
end
y = zeros(1,n);
ind0 = ~isnan(ind);
y(ind0) = x(ind(ind0))

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

その他の回答 (1 件)

KSSV
KSSV 2021 年 6 月 2 日
A = [0 89 90 0 99 100 0] ;
id1 = find(A,1,'first')
id1 = 2
id2 = find(A,1,'last')
id2 = 6

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by