How do I obtain the length of rows in a matrix while excluding the NaN values that occur at the end of each row (but not excluding NaN values mid-row_
1 view (last 30 days)
Show older comments
Monique Chatterton
on 4 Jul 2021
Commented: Monique Chatterton
on 5 Jul 2021
I would like to tally the length of values for each row of a matrix, while exluding the NaNs that occur from each row, but specifically only those NaNs that occur at the end of each row. So for example, for the following:
X =
4 6 7 NaN 4 98 NaN 9 5 34 49 NaN NaN NaN
5 4 23 98 1 2 4 NaN 3 56 78 64 NaN NaN
4 7 8 NaN 9 NaN NaN NaN NaN NaN NaN NaN NaN NaN
The answer to the first row would be 11, because I want a count of all values incudings NaNs that occur in the middle of the row, but not the last NaNs. The answer to the second row would be 12. The answer to the third row would be 5.
How do I do this?
0 Comments
Accepted Answer
Image Analyst
on 4 Jul 2021
Try using isnan() and find():
X = [
4 6 7 NaN 4 98 NaN 9 5 34 49 NaN NaN NaN
5 4 23 98 1 2 4 NaN 3 56 78 64 NaN NaN
4 7 8 NaN 9 NaN NaN NaN NaN NaN NaN NaN NaN NaN]
[rows, columns] = size(X);
for row = 1 : rows
thisRow = X(row, :);
% Find the last number's index
lastIndex = find(~isnan(thisRow), 1, 'last')
end
You get:
X =
4 6 7 NaN 4 98 NaN 9 5 34 49 NaN NaN NaN
5 4 23 98 1 2 4 NaN 3 56 78 64 NaN NaN
4 7 8 NaN 9 NaN NaN NaN NaN NaN NaN NaN NaN NaN
lastIndex =
11
lastIndex =
12
lastIndex =
5
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!