Take a matrix of integers and convert to a binary matrix

1 次查看(过去 30 天)
I have a matrix of random integers, but the rows are sorted numerically from 1-10. I would like to convert these integers into positions of a binary matrix, so each integer in the matrix represents a position labelled 1 in the binary matrix.
e.g As a smaller scale example, (cause my final integer matrix is very large) Say I have a matrix given by
1 6 8
3 5 7
2 4 9
I would want this converted to a 10 x 3 matrix that reads
1 0 0 0 0 1 0 1 0 0
0 0 1 0 1 0 1 0 0 0
0 2 0 1 0 0 0 0 1 0
Many thanks

回答(1 个)

Akira Agata
Akira Agata 2018-9-4
One simple and straight-forward way is using for-loop, like:
A = [1 6 8; 3 5 7; 2 4 9];
B = zeros(3,10);
for kk = 1:3
B(kk,A(kk,:)) = 1;
end
The result is:
>> B
B =
1 0 0 0 0 1 0 1 0 0
0 0 1 0 1 0 1 0 0 0
0 1 0 1 0 0 0 0 1 0

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by