I have a 3D matrix n x m x p where p represents 1400 daily 2D data arrays. I also have a logical array the length of p x 1.
How do I create a new 3D matrix that contain only the 'pages' where p=1?
I have a 3D matrix n x m x p where p represents 1400 daily 2D data arrays. I also have a logical array the length of p x 1.
How do I create a new 3D matrix that contain only the 'pages' where p=1?
This should work in the same way as logical indexing for 1D or 2D arrays.
n = 3; m = 4; p = 5;
tmp = rand([n,m,p]);
p_mask = logical([1 0 1 0 0]);
new = tmp(:,:,p_mask);
A small caveat is, that the "logical" array has to be of the logical
type.
If you use a double array with ones and zeros, Matlab will assume that you want to do regular (positional) indexing and complain because you're trying to access the element at the index 0 which is out-of-bounds:
Index in position 3 is invalid. Array indices must be positive integers or logical values.
Edit: The cast to the logical
type above just serves to illustrate the point about "logical" indexing only working with the logical type, and not with floating point or integer types. Usually, the logical indices would instead be defined by some condition like for example p_mask = p_vals == 1;
where p_vals
would be the array containing ones and zeros. It's of course also not necessary to create a new variable for the logical mask - new = tmp(:,:,p_vals == 1)
would also do just fine.
In MATLAB pulling pages or slices off this n*m*p
matrix is as simple as choosing what pages to take.
np=1400
n=3;m=3; % page size, just as example
A=randi([-20 20],n,m,np); % the n x m x p input matrix
p=randi([0 1],1,np); % selector
p_selection=find(p==1);
B=A(:,:,p_selection); % selected pages