问题
I have a sat of matrices and I want to extract only a part of the matrix that satisfy a condition.
For example: values of the 150x180
matrix goes from 0
to 2.80
and I only want those between 1.66
and 1.77
I want to keep the values within the rang in their original location in the original matrix and set the other to zero.
can anybody help me please.
Thank you
回答1:
You can use logical indexing. First, find A
entries that do not satisfy your conditions. Next, using A(idx)
change them to 0:
% example matrix
A = 2.8*rand(150, 180);
% find entries meeting some criterion
idx = A<1.66 | A>1.77;
A(idx) = 0;
Or simpler, as Rody Oldenhuis suggested, you can include the logical expression directly in the matrix reference:
A(A<1.66 | A>1.77) = 0;
This yields a shorter and cleaner code, but not a faster code: MATLAB still explicitly creates the logical index variable, but clears it afterwards.
来源:https://stackoverflow.com/questions/12781736/how-to-extract-a-part-of-a-matrix-with-condition-in-matlab