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?
Vector Indexing, or vector index notation, specifies elements within a vector. Indexing is useful when a MATLAB program only needs one element of a series of values. Indexing is often used in combination with repetition structures to conduct the same process for every element in an array.
k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.
Description. Returns a matrix of integers indicating their row number in a matrix-like object, or a factor indicating the row labels.
In R, the indexing begins from 1. While NA and zero values are allowed as indexes, rows of an index matrix containing a zero are ignored, whereas rows containing an NA produce an NA in the result.
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
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With