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

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 件のコメント

James Tursa
James Tursa 2016 年 2 月 25 日
In your example, the "25" rows are ordered by the types 1, 2, 3. But in the "63" rows, they are ordered by the types 3, 2, 1. Is this how you really want it? I.e., you don't want it always ordered by 1, 2,3, but you want the output ordered by how the arrangement is in A?
Moe
Moe 2016 年 2 月 25 日
Thanks James,
I want it always ordered by 1, 2,3.

サインインしてコメントする。

 採用された回答

James Tursa
James Tursa 2016 年 2 月 25 日
編集済み: James Tursa 2016 年 2 月 25 日

0 投票

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;
Adata = A(2:m,2:n);
Bcol1 = ones(n1,1)*A(2:m,1)';
Bdata = reshape(bsxfun(@eq,(1:n1)',Adata(:)'),[],n1);
B = [A(1,:); Bcol1(:) Bdata];

3 件のコメント

Moe
Moe 2016 年 2 月 25 日
編集済み: Moe 2016 年 2 月 27 日
Thanks James,
Where you define the total number of variables in Adata? For example, in the above A matrix, we have 3 variables (1,2,3). However, if I changed matrix A as follows:
A = [0 240 245 250
25 1 2 1
63 3 2 4];
the total number of variables should be equal by 4 (1,2,3,4) and in result matrix B dimension should be 9*4.
I made this change in your code:
[m,n] = size(A);
n1 = n - 1;
Adata = A(2:m,2:n);
Bcol1 = ones(4,1)*A(2:m,1)';
Bdata = reshape(bsxfun(@eq,(1:4)',Adata(:)'),[],n1);
B = [A(1,:); Bcol1(:) Bdata];
I added "4" instead of n1 in the Bcoll and Bdata lines.
Image Analyst
Image Analyst 2016 年 2 月 27 日
I'm curious why you need this strange array. What do you want to do once you have it? There may be a more straightforward or simpler way of accomplishing that.
Moe
Moe 2016 年 2 月 29 日
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?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

Moe
2016 年 2 月 25 日

コメント済み:

Moe
2016 年 2 月 29 日

Community Treasure Hunt

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

Start Hunting!

Translated by