Creating an array based on values in a vector

6 vues (au cours des 30 derniers jours)
John Jendzurski
John Jendzurski le 18 Jan 2012
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!

Réponse acceptée

Walter Roberson
Walter Roberson le 18 Jan 2012
bsxfun(@eq,[1 1 3 2 3].',1:3)
  1 commentaire
John Jendzurski
John Jendzurski le 18 Jan 2012
Wow. Very cool, Walter! I did not even know about bsxfun(). Thanks!!!

Connectez-vous pour commenter.

Plus de réponses (1)

the cyclist
the cyclist le 18 Jan 2012
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 commentaire
John Jendzurski
John Jendzurski le 18 Jan 2012
Nice! I like this too. Thanks!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by