Binarize a metrix with some threshold

41 views (last 30 days)
Tamir Eisenstein
Tamir Eisenstein on 16 Mar 2020
Commented: Arthur Roué on 16 Mar 2020
Hi Matlab experts,
How can I binarize a matrix according to a certain threshold? for exapmle the highest 400 values or the highest 20% of the values?
Thanks!
Tamir

Answers (2)

Bhaskar R
Bhaskar R on 16 Mar 2020
Edited: Bhaskar R on 16 Mar 2020
A = randi([0, 1000], 5) % dummy marix
A =
392 277 317 766 646
656 46 951 795 710
171 97 34 187 755
706 824 439 490 276
31 695 381 446 680
>> A>400 % command to compare with 400 threshold
ans =
5×5 logical array
0 0 0 1 1
1 0 1 1 1
0 0 0 0 1
1 1 1 1 0
0 1 0 1 1
>> A>(400*0.2)
ans =
5×5 logical array
1 1 1 1 1
1 0 1 1 1
1 1 0 1 1
1 1 1 1 1
0 1 1 1 1
  1 Comment
Tamir Eisenstein
Tamir Eisenstein on 16 Mar 2020
Dear Bhaskar, thank you, but I think you misunderstood my two examples:
1) Let's say I have a matrix with 1000 components - I want the highest 400 values to be assigned a value of 1, and the rest to become 0.
2) Let's say I have a matrix with 1000 components - I want the highest 20% values to be assigned a value of 1, and the rest to become 0.

Sign in to comment.


Arthur Roué
Arthur Roué on 16 Mar 2020
You can use the 2nd output of sort function.
The code bellow should do what you want.
% Random matrix
M = randi([0, 1000], 5);
M =
699 480 806 28 500
198 905 577 490 471
30 610 183 168 59
744 618 240 979 682
500 860 887 713 42
% Sort
[~,I1] = sort(M(:));
[~,I2] = sort(flipud(I1)); % flip for ascending order
% Reshape
Index = (1:numel(M))';
Index = Index(I2);
Index = reshape(Index, size(M));
Index =
8 16 5 25 13
19 2 12 15 17
24 11 20 21 22
6 10 18 1 9
14 4 3 7 23
% For the 5 greatest values
Index <= 5
ans =
5×5 logical array
0 0 1 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 1 0
0 1 1 0 0
  2 Comments
Image Analyst
Image Analyst on 16 Mar 2020
Or you can use the other input of sort() to avoid flipping:
[sortedI1, sortOrder] = sort(I1, 'ascend'); % No need to flip for ascending order
Arthur Roué
Arthur Roué on 16 Mar 2020
Indeed, you could to that, thanks for the complement.

Sign in to comment.

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!