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 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Image Analyst
2021-7-4
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!