Finding Last Non-Zero Value For Each Row

조회 수: 31 (최근 30일)
Derrick Vaughn
Derrick Vaughn 2021년 5월 11일
댓글: Image Analyst 2021년 5월 11일
I have a 50x50 matrix (let's call it data) and I'm trying to find the last non-zero value for each row of the matrix. So far looking through other questions, I've seen answers for finding the positions of the last non-zero values or for applying this idea to arrays, but nothing on producing the actual values for a matrix. Any help is appreciated, thanks!

채택된 답변

Image Analyst
Image Analyst 2021년 5월 11일
Try this:
% Sample data
m = randi([0, 1], 10, 10)
[rows, columns] = size(m)
% Create an array to keep track of the column of the last 1 in each row.
lastNonZeroColumn = zeros(rows, 1);
% Loop over rows, finding the last 1 in each row.
for row = 1 : rows
% Find the last 1 in this row, if any exist.
col = find(m(row, :), 1, 'last');
if ~isempty(col)
% At least one 1 exists. Log it's location.
lastNonZeroColumn(row) = col;
end
end
% Display results in command window:
lastNonZeroColumn
  댓글 수: 2
Derrick Vaughn
Derrick Vaughn 2021년 5월 11일
Hi, thanks for this but this gives me the column position for the last nonzero value. I'm trying to get the values, not the position. Is there any way to take your product above and extract the values?
Image Analyst
Image Analyst 2021년 5월 11일
So just log that value also:
% Sample data
m = randi([0, 9], 10, 10)
[rows, columns] = size(m)
% Create an array to keep track of the column of the last 1 in each row.
lastNonZeroColumn = zeros(rows, 1);
dataValues = nan(rows, 1);
% Loop over rows, finding the last 1 in each row.
for row = 1 : rows
% Find the last 1 in this row, if any exist.
col = find(m(row, :), 1, 'last');
if ~isempty(col)
% At least one 1 exists. Log it's location.
lastNonZeroColumn(row) = col;
dataValues(row) = m(row, col);
end
end
% Display results in command window:
lastNonZeroColumn
dataValues

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Time Series Collections에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by