如何找到3-D矩阵的非零元素的坐标? [英] How to find the coordinates of nonzero elements of a 3-D matrix?

查看:129
本文介绍了如何找到3-D矩阵的非零元素的坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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?

推荐答案

如果要更改矩阵的非零/零值,请使用逻辑索引 @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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆