Retrieve all non-zeros indices except the first one for each row

1 次查看(过去 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

采纳的回答

Image Analyst
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
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.
Romeo Tahal
Romeo Tahal 2020-3-8
Well sir,
There is an issue with the sequence of the indices. Using the code, I get the following sequence for the row indices:
11 0 7 17 0 23 0 14 0 10 25 0
This is because the indices for the rows are row-based, but matlab uses column-wise ordering. The correct sequence should be: 11 7 10 17 14 25 0 23 0 0 0 0
How can I get this ordering? What change(s) do I have to make in the code for the row indices?
Thanks in advance.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by