Finding Last Non-Zero Value For Each Row

20 Ansichten (letzte 30 Tage)
Derrick Vaughn
Derrick Vaughn am 11 Mai 2021
Kommentiert: Image Analyst am 11 Mai 2021
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!

Akzeptierte Antwort

Image Analyst
Image Analyst am 11 Mai 2021
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 Kommentare
Derrick Vaughn
Derrick Vaughn am 11 Mai 2021
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 am 11 Mai 2021
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Time Series Collections finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by