Vectorizing the creation of an (m x n) matrix where each row represents a number

I am trying to create an (m x n) matrix where every row represents a number. For instance, let's say I wanted to represent the following numbers:
y = [1:3]'
y =
1
2
3
Then that could be represented as:
yk = [1 0 0; 0 1 0; 0 0 1]
yk =
1 0 0
0 1 0
0 0 1
Right now I am using the following code:
yk = zeros(m,n);
for i = 1:m
yk(i,y(i)) = 1;
end
But I would like to vectorize it to get rid of the FOR loop. Anyone know how to do this?

Réponses (3)

the cyclist
the cyclist le 16 Jan 2017
Modifié(e) : the cyclist le 16 Jan 2017
I'm not sure how your matrix "represents" the vector. I feel that you have not presented a general enough rule for what you want.
Do you just want
eye(3)
?

1 commentaire

Apologies about that. Basically the "n" should be what range of possible values the number could be. So if the set of numbers could be 1:5 (only integers), the n = 5 and (for e.g.) 3 would be represented by [0 0 1 0 0]
Assuming y is a column vector
yk = zeros(m,n);
yk((1:m)+m*(y-1)) = 1;

Cette question est clôturée.

Tags

Clôturé :

le 20 Août 2021

Community Treasure Hunt

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

Start Hunting!

Translated by