Retrieve all non-zeros indices except the first one for each row
3 次查看(过去 30 天)
显示 更早的评论
Hi, I have the following question. How can I retrieve all nonzero indices of each row except the first nonzero index in a matrix? Suppose I have the following matrix:
A = [2 0 1 0 0; 4 -9 0 5 0;0 0 2 0 -3;0 -3 2 0 0;1 2 0 0 6];
I would like the output to be: 11, 0, 7, 17, 0, 23, 0, 14, 0, 10, 25, 0 as the linear indices.
If there are no more non-zeros in a row after the last one, then the index is zero.
-Thanks in advance-
Romeo
0 个评论
采纳的回答
Image Analyst
2020-2-27
Zero cannot be a linear index. This code will work:
A = [2 0 1 0 0; 4 -9 0 5 0;0 0 2 0 -3;0 -3 2 0 0;1 2 0 0 6]
linearIndexes = [];
for row = 1 : size(A, 1)
% Find columns where A is nonzero
indexes = find(A(row,:) ~= 0);
% Tack on the second and other elements more to the right in this row.
for k = 2 : length(indexes)
% Get the linear index for this (row, column) location.
linearIndex = sub2ind(size(A), row, indexes(k));
% Tack it on to our accumulating/growing output variable.
linearIndexes(end+1) = linearIndex;
end
end
linearIndexes % Echo to command window.
It shows
A =
2 0 1 0 0
4 -9 0 5 0
0 0 2 0 -3
0 -3 2 0 0
1 2 0 0 6
linearIndexes =
11 7 17 23 14 10 25
Same as you except for no zeros.
7 个评论
Image Analyst
2020-2-28
Seems complicated. MATLAB has capability to deal with sparse matrices. Why not just use it and not have this complicated scheme? Are the matrices so gigantic, even when sparse, that you're running out of memory? Well anyway, good luck.
更多回答(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!