Row wise indexing of 3d array

조회 수: 5 (최근 30일)
Oscar Frick
Oscar Frick 2018년 6월 14일
댓글: Oscar Frick 2018년 6월 15일
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에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by