MATLAB: How to assign NaN in matrix by masking

findmaskingmatrixmatrix arraynan

Hello everyone,
I have two matrices, matrix1 is three dimensional 180 x 360 x 12 (latitude x longitute x months) and matrix2 is two dimensional 180 x 360
In matrix one I want to assign NaN in entire matrix excluding some columns and some rows. column and row number found from second matrix using following code:
% mask = 100;
% [x y] = find(matrix2 == mask); %%%%by this I found the x and y coordinates.
Now how can I assign NaN in entire matrix1 excluding x and y coordinates which is found by matrix2 ? Can anyone help in this regard? I'll be thankful.

Best Answer

Logical indexing is your friend! find() is a little slow because it can't predict how many matches there will be, so it can't preallocate the output vectors and keeps resizing those vectors every time a new match is found.
The "logical" solution:
matrix1(~(matrix2 == mask)) = nan
(matrix2 == mask) is a boolean matrix, with 1 indicating it matches the mask. The ~ operator flips the 0's and 1's, so 1 indicates it doesn't match the mask. And you can supply this matrix as the indices to matrix1, and assign nan as the scalar.