Row wise indexing of 3d array
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Oscar Frick
le 14 Juin 2018
Commenté : Oscar Frick
le 15 Juin 2018
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 commentaires
Réponse acceptée
Guillaume
le 14 Juin 2018
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 commentaires
James Tursa
le 14 Juin 2018
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
Plus de réponses (1)
Mark Saad
le 14 Juin 2018
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 commentaires
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!