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

matrix arrayrows

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

Best Answer

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.