I am trying to find the coordinates of all non zero elements in a matrix, in MATLAB. I know that find
makes this very easy. The problem is that I need to define the length of my matrix before I can fill it up. I believe this is impossible using find
, since it will make its own vector.
So I have to find another way. If I'm looking for 1 element it will be easy as well. Let me use an example. Say I have a matrix M
of 500×500, with 60
ones somewhere. I want to find the coordinates. So I can start with:
for i = 1:500
for j = 1:500
if M(i,j) == 1
row = i;
col = j;
end
end
end
But I want more then one point, and I need to define the length of a vector before filling it. So I'll make the gamble that there are less then 100 ones in the matrix:
v = zeros(1,100)
w = zeros(1,100)
And how I essentially want to fill this vector is as follows. Let's say I have already filled N
elements of the vector, so the next one will be:
for i = 1:500
for j = 1:500
if M(i,j) == 1 && i ~= v(1) && i ~= v(2) && ... && i ~= v(N) && j ~= v(1) && ... && i ~= v(N)
v(N+1) = i
w(N+1) = j
end
end
end
So I need another for loop containing all this, which will run through the elements of the vectors v
and w
, and I need some loop that will make sure the right if statement is being used.
Does anyone have any idea of how to do this?
Kind regards,
Jesse