MATLAB: Finding last non-zero value from column

column

Given a matrix looking something like e.g. M = [ 1 1 1 1 1 1 ; 1 1 1 0 0 0 ; 1 1 0 0 0 0 ; 1 0 0 0 0 0; 0 0 0 0 0 0 ];
How can I find the coordinate (for plotting these values as a line) for which states the last non-zero element in each column?
For this example I want the coordinates for the column number [ 4, 3, 2, 1, 1, 1]
Would the same code work for 3D-matrix?

Best Answer

M = [ 1 1 1 1 1 1 ; 1 1 1 0 0 0 ; 1 1 0 0 0 0 ; 1 0 0 0 0 0; 0 0 0 0 0 0 ];
n=M~=0;
[dummy,Index]=sort(n);
Index=Index(end,:).*any(n)
Use M=randint(x,y) to generate testing data, I am thinking my solution has an edge.
for 3D matrix:
clear M;clc;
M(1,:,:) = [ 1 1 1 1 1 1 ; 1 1 1 0 0 0 ; 1 1 0 0 0 0 ; 1 0 0 0 0 0; 0 0 0 0 0 0 ];
M(2,:,:) = [ 1 1 1 1 1 1 ; 1 1 1 1 1 1 ; 1 1 1 1 1 0 ; 1 1 1 1 0 0; 1 1 1 0 0 0 ];
M(3,:,:) = [ 1 1 1 1 1 1 ; 1 1 1 1 1 0 ; 1 1 1 1 1 0 ; 1 1 1 1 0 0; 1 1 1 1 0 0 ];
M(4,:,:) = [ 1 0 0 0 0 0 ; 1 0 0 0 0 0 ; 1 1 0 0 0 0 ; 1 1 0 0 0 0; 1 1 0 0 0 0 ];
n=M~=0;
[dummy,Index]=sort(n,2);
Index=Index(:,end,:).*any(n,2);
Index=reshape(Index,size(M,1),size(M,3))