问题
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
回答1:
Here's another way, nice & wasteful:
[jj,ii] = meshgrid(1:size(M,2),1:size(M,1));
inds = M~=0;
ii = ii(inds);
jj = jj(inds);
回答2:
I honestly cannot understand what's wrong with find.
But, if you insist on your own implementation using nested loop, then
v = NaN(100,1);
w = NaN(100,1); % pre-allocate
ii=1;
for row=1:size(M,1)
for col=1:size(M,2)
if M(row,col) == 1
v(ii)=row;
w(ii)=col;
ii=ii+1; %counts howmany elements were found
end
end
end
v(isnan(v))=[]; %discard redundent elements
w(isnan(w))=[];
来源:https://stackoverflow.com/questions/22501926/implementing-the-matlab-find-function