Row wise indexing of 3d array

5 次查看(过去 30 天)
I have a 3d array, for example:
(:,:,1)
-0.1468 -0.4846 -0.3310
0.3212 -0.4570 0.1491
(:,:,2)
-0.3110 -0.3165 0.1256
0.1868 -0.1315 0.2802
(:,:,3)
-0.4189 0.2757 -0.0641
0.4294 -0.0132 -0.0532
What I want to do is find all values of the last column (:,3,:) that is less than 0, and then set the corresponding rows to NaN. In the above case, the results should be:
(:,:,1)
NaN NaN NaN
0.3212 -0.4570 0.1491
(:,:,2)
-0.3110 0.3165 0.1256
0.1868 -0.1315 0.2802
(:,:,3)
NaN NaN NaN
NaN NaN NaN
I can achieve it in the 2d case using the following code:
array = rand(5,3)-0.5
array(find(array(:,3)<0),:) = NaN
But I struggle with the 3d case.

采纳的回答

Guillaume
Guillaume 2018-6-14
Note that in the 2D case you didn't need find (which only slows things done):
array(array(:, 3) < 0, :) = NaN;
For the ND case it's a bit more complicated since the result of the comparison is a matrix not a single dimension vector. One possibility:
array(repmat(array(:, 3, :) < 0, 1, size(array, 2), 1)) = NaN
  2 个评论
James Tursa
James Tursa 2018-6-14
On earlier versions of MATLAB that trailing argument of repmat will not work. So just this:
array(repmat(array(:, 3, :) < 0, 1, size(array, 2))) = NaN
Oscar Frick
Oscar Frick 2018-6-15
This works perfectly as well as being effective. Some short testing I did seems to indicate that the version without the trailing argument has an extremely slight time advantage when having "small" arrays (on the format (n,3,4), small being size seems to be about n<10000000). For larger arrays the version with the trailing one starts getting ahead, getting a more significant efficiency advantage as the arrays grow bigger.

请先登录,再进行评论。

更多回答(1 个)

Mark Saad
Mark Saad 2018-6-14
You could try:
[I,J,K] = ind2sub(size(array), find(array(:,:,:) < 0));
ind = find(J == 3);
I = I(ind);
J = J(ind);
K = K(ind);
array(I,:,K) = NaN;
The first line gets the indices of every value that is less than 0. Lines 2-4 filter out any indices not in the third column. The last line sets the desired values to NaN.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by