Convert a vector to a binary matrix

6 ビュー (過去 30 日間)
Utkarsh Barsaiyan
Utkarsh Barsaiyan 2018 年 1 月 2 日
編集済み: Pawel Jastrzebski 2018 年 1 月 2 日
y = [1; 1; 2; 3; 4; 4];
I want to convert this to a matrix such that in each row the corresponding element is 1 and the rest are zero.
y = [1 0 0 0;
1 0 0 0;
0 1 0 0;
0 0 1 0;
0 0 0 1];
What is the best way to do this preferably without using loops?

採用された回答

Guillaume
Guillaume 2018 年 1 月 2 日
Use sub2ind to transform row/column coordinates in linear indices and use that linear index to assign to your destination matrix:
y = [1; 1; 2; 3; 4; 4];
newy = zeros(numel(y), max(y));
newy(sub2ind(size(newy), 1:numel(y), y')) = 1

その他の回答 (1 件)

Pawel Jastrzebski
Pawel Jastrzebski 2018 年 1 月 2 日
編集済み: Pawel Jastrzebski 2018 年 1 月 2 日
With LOOP:
y = [1; 1; 2; 3; 4; 4];
nRow = length(y);
nCol = max(y);
A = zeros(nRow,nCol);
for i=1:nRow
A(i,y(i)) = 1;
end
A
WITHOUT LOOP:
y1 = [1; 1; 2; 3; 4; 4];
nRow1 = length(y1);
nCol1 = max(y1);
A1 = zeros(nRow1,nCol1);
index = (y1-1).*nRow1+(1:nRow1)';
A1(index) = 1;
A1
  2 件のコメント
Birdman
Birdman 2018 年 1 月 2 日
What is the best way to do this preferably without using loops?
Do not use loop.
Utkarsh Barsaiyan
Utkarsh Barsaiyan 2018 年 1 月 2 日
Yes, this is the basic thing. I am looking for an answer that does it without using loops. For eg., I create an array of zeros of the corresponding size then make all the elements corresponding to the columns in y to be 1.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by