Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

matlab - How to find the coordinates of nonzero elements of a 3-D matrix?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...