MATLAB: Indexing a 3D array with a vector

3d arrayindexingMATLAB

% 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

Best Answer

c = b(:,3,:);
c(c > 5) = -100;
b(:,3,:) = c;