I am trying to mask values in a matrix that are out of a specified range and trying to make a new matrix from the values after the values out of the range have been masked.

52 views (last 30 days)
I am trying to mask values in a matrix that were calculated using values of theta. I am trying to mask values that are less that 20 deg. From the values that have not been masked I am trying to make a new matrix
i.e.
Gamma - matrix before mask values
gamma - new matrix after values have been masked
gamma = (somefunction to mask Gamma)

Accepted Answer

Voss
Voss on 18 Feb 2022
Edited: Voss on 18 Feb 2022
It's not entirely clear exactly what you have in mind, but one or more of these options should cover it. If not, please explain further.
% some theta values:
theta = [0:4 5:5:30]
theta = 1×11
0 1 2 3 4 5 10 15 20 25 30
% calculate Gamma using some function of theta:
Gamma = theta.^2
Gamma = 1×11
0 1 4 9 16 25 100 225 400 625 900
% take the values of Gamma greater than or equal to 20:
gamma = Gamma(Gamma >= 20)
gamma = 1×6
25 100 225 400 625 900
% or take the values of Gamma where theta was greater than or equal to 20:
gamma = Gamma(theta >= 20)
gamma = 1×3
400 625 900
% or set the values of Gamma less than 20 to NaN
gamma = Gamma;
gamma(Gamma < 20) = NaN
gamma = 1×11
NaN NaN NaN NaN NaN 25 100 225 400 625 900
% or set the values of Gamma less than 20 to 0
gamma = Gamma;
gamma(Gamma < 20) = 0
gamma = 1×11
0 0 0 0 0 25 100 225 400 625 900
% or set the values of Gamma where theta was less than 20 to NaN
gamma = Gamma;
gamma(theta < 20) = NaN
gamma = 1×11
NaN NaN NaN NaN NaN NaN NaN NaN 400 625 900
% or set the values of Gamma where theta was less than 20 to 0
gamma = Gamma;
gamma(theta < 20) = 0
gamma = 1×11
0 0 0 0 0 0 0 0 400 625 900
All of these operations are examples of logical indexing.

More Answers (1)

DGM
DGM on 18 Feb 2022
Edited: DGM on 18 Feb 2022
This is all still terribly nonspecific. "Masking" may be generally read as "selecting". What is to happen to the undesired elements? Are they set to zero? To NaN? ... or do the workflow allow the extraction of the desired elements alone, perhaps as a vector?
Consider the array of angles:
A = reshape(round(linspace(0,40,25)),5,5)
A = 5×5
0 8 17 25 33 2 10 18 27 35 3 12 20 28 37 5 13 22 30 38 7 15 23 32 40
mask = A<20
mask = 5×5 logical array
1 1 1 0 0 1 1 1 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0
% set masked values to 0
B = A;
B(mask) = 0
B = 5×5
0 0 0 25 33 0 0 0 27 35 0 0 20 28 37 0 0 22 30 38 0 0 23 32 40
% set masked values to NaN
C = A;
C(mask) = NaN
C = 5×5
NaN NaN NaN 25 33 NaN NaN NaN 27 35 NaN NaN 20 28 37 NaN NaN 22 30 38 NaN NaN 23 32 40
% extract vector of unmasked values
D = A(~mask)
D = 13×1
20 22 23 25 27 28 30 32 33 35

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!