I'm not sure if you mean to do this in y1
or y2
. In any case, try this (on y1
for example):
y = randi(10,5000,1);
y1 = zeros(size(y,1), 10);
y1(sub2ind(size(y1), (1:size(y1,1))', y)) = 1;
Question
I have a vector y
with integer values from 1 to 10:
octave> size(y)
ans =
5000 1
I created zeros
array y1
:
octave> size(y1)
ans =
5000 10
I need to set 1
in each row of y2
, in the element with index equal to value in y
. So in first row, when I have:
octave> y(1)
ans = 10
I need to have:
octave> y1(1,:)
ans =
0 0 0 0 0 0 0 0 0 1
Something reverse to [w, y] = max(y2, [], 2);
I have in other places of my code.
Is there a simple one-line trick to do that? And if not, how can I iterate over both arrays simultaneously?
La solution 2
I'm not sure if you mean to do this in y1
or y2
. In any case, try this (on y1
for example):
y = randi(10,5000,1);
y1 = zeros(size(y,1), 10);
y1(sub2ind(size(y1), (1:size(y1,1))', y)) = 1;
Autres conseils
You can use this trick
y1 = eye(10)(y,:);
or it's two-step version
y1 = eye(10);
y1 = y1(y,:);
In first step you create a identity matrix
>> y1 = eye(10)
y1 =
Diagonal Matrix
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
In the second step you use y
as index in the indentity matrix. This step literally copy rowsfrom identity matrix and create desired matrix.
>> y = [1,1,2,2,5,10,10];
>> y1 = y1(y,:)
y1 =
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 1
Don't know a one line trick but you can do it in a one simple loop:
for i=1:length(y)
y1(i,y(i))=1;
end