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.
댓글 수: 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!