Finding Last Non-Zero Value For Each Row

31 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Image Analyst
Image Analyst il 11 Mag 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 Commenti
Derrick Vaughn
Derrick Vaughn il 11 Mag 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 il 11 Mag 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Time Series Collections in Help Center e File Exchange

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by