Creating an array based on values in a vector

6 ビュー (過去 30 日間)
John Jendzurski
John Jendzurski 2012 年 1 月 18 日
MATLAB gurus! Can ya'll help me with this one? I've got a column vector of integers ranging from 1 to N. I want to create an array with the same number of rows and N columns, where each element of a row is 'zero' except for a 'one' in the column corresponding to the integer in the row of the original vector. For example, consider N = 3 and given the column vector X = [1 1 3 2 3]'. I want to create the following array:
Y = [1 0 0; 1 0 0; 0 0 1; 0 1 0; 0 0 1]
Obviously loops and so forth would accomplish this, but I am wondering if it can be done with just simple matrix algebra. Thanks!

採用された回答

Walter Roberson
Walter Roberson 2012 年 1 月 18 日
bsxfun(@eq,[1 1 3 2 3].',1:3)
  1 件のコメント
John Jendzurski
John Jendzurski 2012 年 1 月 18 日
Wow. Very cool, Walter! I did not even know about bsxfun(). Thanks!!!

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

その他の回答 (1 件)

the cyclist
the cyclist 2012 年 1 月 18 日
Here's one way:
N = 3;
X = [1 1 3 2 3]';
L = numel(X);
Y = zeros(L,N);
linearIndex = sub2ind([L,N],(1:L)',X);
Y(linearIndex) = 1;
  1 件のコメント
John Jendzurski
John Jendzurski 2012 年 1 月 18 日
Nice! I like this too. Thanks!

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by