Creating an array based on values in a vector

조회 수: 2 (최근 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;

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by