Finding Last Non-Zero Value For Each Row

20 visualizaciones (últimos 30 días)
Derrick Vaughn
Derrick Vaughn el 11 de Mayo de 2021
Comentada: Image Analyst el 11 de Mayo de 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!

Respuesta aceptada

Image Analyst
Image Analyst el 11 de Mayo de 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 comentarios
Derrick Vaughn
Derrick Vaughn el 11 de Mayo de 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 el 11 de Mayo de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Time Series Collections en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by