Finding Last Non-Zero Value For Each Row
20 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
0 Kommentare
Akzeptierte Antwort
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
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Time Series Collections finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!