Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
Romeo Tahal
Romeo Tahal le 27 Fév 2020
Commenté : Romeo Tahal le 8 Mar 2020
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

Réponse acceptée

Image Analyst
Image Analyst le 27 Fév 2020
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 commentaires
Image Analyst
Image Analyst le 28 Fév 2020
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 le 8 Mar 2020
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by