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

909 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

You can also use spy() but you need to adjust the tick labels.

Suppose you have the following matrix:

A = rand(418,284)>.7;

Then:

spy(A)

enter image description here

Adjusting the labels:

yticks = get(gca, 'YTick');
yticks(yticks ~= 0) = -yticks(yticks ~= 0);
set(gca, 'YTickLabel', yticks)

enter image description here