如何找到3-D矩阵的非零元素的坐标? [英] How to find the coordinates of nonzero elements of a 3-D matrix?
问题描述
我有一个3D矩阵A
,其大小是40*40*20
的两倍. 3D矩阵中的值为"0"
或"1"
.矩阵A中"1"
的数量为50.我知道如何找到3D矩阵的相应坐标.代码如下:
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];
我的问题是如何只找到3D矩阵A
中非零元素的坐标[xi yi zi] (i=1,2,...,50)
,然后将值a1, a2, a3, ..., a50
分配给相应的坐标[xi yi zi] (i=1,2,...,50)
,还将"NaN"
值分配给其他坐标是否为零?
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 ,您不需要find
或 ind2sub
. @patrik 在注释中给出了将零值更改为NaN的技术:
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));
注意:您可以用以下任何一种替换上面的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-D矩阵的非零元素的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!