필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Romeo Tahal
Romeo Tahal 2020년 2월 27일
댓글: Romeo Tahal 2020년 3월 8일
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