Indexing a 3D array with a vector
16 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
% My question is best explained with an example;
% I would like to change each of the elements in column three of each page of exampleData to -100,
% if they are greater than 5. I have done this with a for loop, but would like to know if there is
% a more elegant way, using assignments.
% Creating example data;
x = [[1,2,3,4];[5,6,7,8];[2,8,9,7]];
y = [[1,3,5,3];[7,9,0,2];[2,4,5,4]];
z = [[2,4,6,6];[3,5,7,1];[8,9,3,3]];
exampleData = cat(3,x,y,z);
% For loop method - this gets the desired result, but I am interested to see if it can be done
% via an assignement;
b = exampleData; % using "b" just to make it more readable.
for pageInd = 1:length(exampleData(1,1,:));
cInd = b(:,3,pageInd)>5;
b(cInd,3,pageInd) = -100;
end
% Assignment method - this does not produce the desired result.
c = exampleData; % using "c" just to make it more readable.
cInd = c(:,3,:)>5;
c(cInd) = -100;
% Thanks very much for any help you give.
% John
>> b (desired result)
b(:,:,1) =
1 2 3 4
5 6 -100 8
2 8 -100 7
b(:,:,2) =
1 3 5 3
7 9 0 2
2 4 5 4
b(:,:,3) =
2 4 -100 6
3 5 -100 1
8 9 3 3
>> c (undesired result)
c(:,:,1) =
1 2 -100 4
-100 6 -100 8
-100 8 9 7
c(:,:,2) =
1 3 5 3
7 9 0 2
2 4 5 4
c(:,:,3) =
2 4 6 6
3 5 7 1
8 9 3 3
0 commentaires
Réponse acceptée
Plus de réponses (1)
pietro
le 12 Nov 2014
try this:
x = [[1,2,3,4];[5,6,7,8];[2,8,9,7]];
y = [[1,3,5,3];[7,9,0,2];[2,4,5,4]];
z = [[2,4,6,6];[3,5,7,1];[8,9,3,3]];
exampleData = cat(3,x,y,z);
[I,J,K] = ind2sub(size(exampleData),find(exampleData>5));
b=exampleData;
for i=1:length(I)
b(I(i),J(i),K(i))=-100;
end
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!