Search code examples
matlabmatrixgraphplotcoordinate-systems

How to plot the coordinates of the nonzero elements in a matrix?


I have a 418x284 matrix filled with 0s and 1s and want to plot a graph where the points are all the location of one's and the x and y coordinates are (0 to 284, 0 to -418).
How can I go about doing this? Thank you for all your help!


Solution

  • Let mat by your binary matrix. You can get the coordinates of the non-zero elements using find:

    [I,J] = find(mat)
    plot(I, J);
    

    Note that the convention for axes is different between images and plots in Matlab. The above code assumes I is the rows index (top to bottom) and J is the columns index (left to right).

    A working example:

    mat=eye(10);
    [I, J]=find(mat);
    
    subplot(1,2,1), imshow(mat)
    subplot(1,2,2), plot(I, J);
    

    Result:

              Binary image                              Non-zero pixels location
    

    enter image description here