How to find the coordinates of nonzero elements of

2019-09-21 03:41发布

I have a 3D matrix A, the size of which is 40*40*20 double. The values in 3D matrix is either "0" or "1". The number of "1" in matrix A is 50. I know how to find the corresponding coordinates of the 3D matrix. The code looks like this:

[x y z] = ind2sub(size(A),find(A));
coords = [x y z];

My question is how to just find the coordinates [xi yi zi] (i=1,2,...,50) of the nonzero elements in 3D matrix A, and then assign values a1, a2, a3, ..., a50 to the corresponding coordinates [xi yi zi] (i=1,2,...,50), also assign "NaN" values to the other coordinates with zero values?

2条回答
贪生不怕死
2楼-- · 2019-09-21 04:13

If you're trying to change the nonzero/zero values of a matrix, using logical indexing 1,2 you don't need find or ind2sub. @patrik gave the technique in the comments for changing the zero values to NaN:

A(A==0) = nan;

You can do the same thing for the nonzero values:

A(A~=0) = a(1:sum(A~=0));

Note: You could replace A~=0 above with any of the following:

~~A
A>0         %// IFF you have no negative values
find(A)     %// but the logical operations are faster
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-09-21 04:25

OK. You already done half of this works. But , if you need some examples here is one: use ind2sub() function to create array with nonzero elements coordinates. I show the 2D example, because it's easy to visualize results:

k = 0;
for i = 1:size(A,1)*size(A,2)
    if A(i) == 1
        [ I(k+1) J(k+1)] = ind2sub(s,i);
        k=k+1;
    end
end

lets take a look at I and J:

A =

 1     0     0     0     1
 1     0     1     0     0
 0     1     1     1     1
 1     1     0     1     1
 1     1     1     1     1
I = 1     2     4     5     3     4     5     2     3     5     3     4     5     1     3     4     5
J = 1     1     1     1     2     2     2     3     3     3     4     4     4     5     5     5     5

so now you can do anything with it. for example, set your values. If we have array of values a:

for k = 1:size(I,2)
A(I(k),J(k)) = a(k);
end

Similarly, you can go this way to create the array of zero elements and to set them Nan. And it works for 3D the same way.

P.S. by the way, I don't understand why you don't want to use just loops like this:

for i: = 1:40
    for j = 1:40
        for k = 1:20
        if A(i,j,k) == 1
            A(i,j,k) = a(l);
            l = l + 1;
        else A(i,j,k) = NaN;
        l = l + 1;
        end
    end
end
查看更多
登录 后发表回答