MATLAB: How to find the index of first and last nonzero elements in each column

identification of non zero elements

Hi,Is there any way to find the index of first and last nonzero element in a matrix?
I have this matrix
A=[0 0 0 0
0 0 0 0
1 0 4 8
2 0 5 9
3 1 6 7
0 2 7 0
0 0 0 0]
as the first non zero element in 1st column is 3 and and the last is 5. In the second column the the 12th element is the first non zero and the last one is 13th etc
I want to store these values in a matrix in which each row represents the index of first non zero element and the 2nd row shows the index of last non zero elements.
the answer matrix should be like this:
B=[3 12 17 24
5 13 21 26]
How can I do this??
Thankyou for time and consideration.I really appreaciate your help.Kindly guide me

Best Answer

You could probably use
A = [0 0 0 0
0 0 0 0
1 0 4 8
2 0 5 9
3 1 6 7
0 2 7 0
0 0 0 0]
[rows, columns] = size(A)
B = zeros(2, columns)
for col = 1 : size(A, 2)
B(1, col) = find(A(:, col), 1, 'first');
B(2, col) = find(A(:, col), 1, 'last');
end
This gives
B =
3 5 3 3
5 6 6 5
which makes sense to me but I'm puzzled as to how you get
B=[3 12 17 24
5 13 21 26]
for your example. Can you explain?