Row wise indexing of 3d array
4 次查看(过去 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.
0 个评论
采纳的回答
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
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
更多回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!