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?
If you're trying to change the nonzero/zero values of a matrix, using logical indexing 1,2 you don't need
find
orind2sub
. @patrik gave the technique in the comments for changing the zero values to NaN:You can do the same thing for the nonzero values:
Note: You could replace
A~=0
above with any of the following: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:lets take a look at
I
andJ
:so now you can do anything with it. for example, set your values. If we have array of values
a
: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: