Converting matrix entries satisfying a threshold condition.

146 views (last 30 days)
Paul Fishback on 29 Jan 2015
Commented: Star Strider on 7 Mar 2020
I have a matrix of numeric entries and wish to convert each entry above a specified threshold to one and all other entries to zero. This has to be an elegant way to do this without a "for" loop. Perhaps using the "find" command in some manner?

1 Comment

Paul Fishback on 29 Jan 2015
Never mind... Forgot I can apply the floor function to a matrix.

Star Strider on 29 Jan 2015
There are likely a number of ways.
One approach:
M = magic(6);
Mm = mean(M(:));
M(M>Mm) = 1;
M(M~=1) = 0;
It sets all the entries greater than the mean to 1, and then uses that result to set the rest to 0.

Image Analyst on 29 Jan 2015
Or, instead of the last 3 lines:
M = M > someThreshold;
Tamir Eisenstein on 6 Mar 2020
What if my threshold is not a specific number but a percentile? for example, set the top 20% values to 1 and the rest to 0.
Star Strider on 7 Mar 2020
@Tamir Eisenstein —
M = randi(99, 10); % Create Matrix
Msort = sort(M(:),'descend'); % Sorted Vector
Threshold = Msort(fix(numel(M)*0.2)); % Find Top 20% Value
Out = zeros(size(M))~=0; % Create Logical Matrix
Out(M >= Threshold) = 1; % Desired Result