# How to transform a matrix to a binary type in Matlab?

4 views (last 30 days)
Moe on 25 Feb 2016
Commented: Moe on 29 Feb 2016
Matrix A is as follows:
A = [0 240 245 250
25 1 2 1
63 3 2 1];
First row is header of the matrix.
Except column1 that is unique id, there are 3 different variables in the matrix. I want matrix A transformed to the binary matrix, like the following matrix:
B = [
0,240,240,250
25,1,0,1
25,0,1,0
25,0,0,0
63,0,0,1
63,0,1,0
63,1,0,0];
Id 25 and 63 repeated 3 times, because there are 3 types of variables. For example, first row: 1,0,1 represents that there was type 1 in the matrix A(2,2) and no type 1 in A(2,3) and 1 in A(2,4).
##### 2 CommentsShowHide 1 older comment
Moe on 25 Feb 2016
Thanks James,
I want it always ordered by 1, 2,3.

James Tursa on 25 Feb 2016
Edited: James Tursa on 25 Feb 2016
E.g., using a loop:
[m,n] = size(A);
n1 = n - 1;
B = zeros((m-1)*n1+1,n);
B(1,:) = A(1,:);
for k=2:m
kx = (k-2)*n1 + 2;
B(kx:kx+n1-1,1) = A(k,1);
B(kx:kx+n1-1,2:n) = bsxfun(@eq,(1:n1)',A(k,2:n));
end
A little bit harder to follow, but without the loop:
[m,n] = size(A);
n1 = n - 1;
Bcol1 = ones(n1,1)*A(2:m,1)';
B = [A(1,:); Bcol1(:) Bdata];
Moe on 29 Feb 2016
Hi Image Analyst,
I need to transform my raw matrix to binary (0,1), then I can use it for clustering. Does it make sense?