问题
I'm trying to get a binary one-of-K coding of a integer vector in Octave. I've got a vector y, say
y = [1 ; 2 ; 3 ; 1 ; 3]
and I want a matrix
Y = [1 0 0
0 1 0
0 0 1
1 0 0
0 0 1]
I can construct the one-of-K matrix by hand with
Y = [];
Y = [Y y == 1];
Y = [Y y == 2];
Y = [Y y == 3];
But when I try to construct it with a for loop,
Y = [];
for i = unique(y),
Y = [Y y == i];
endfor
something goes wrong:
error: mx_el_eq: nonconformant arguments (op1 is 5x1, op2 is 3x1)
I don't even understand the error message. Where's my mistake?
回答1:
I think there's a way to do this without a loop:
Y = unique(y)(:,ones(1,size(y,1)))' == y(:,ones(size(unique(y),1),1))
回答2:
Ok, found it. I wish the tutorial had told me this.
Y = [];
for i = unique(y)',
% ^
% -------------/
Y = [Y y == i];
end
Apparently, for loops through the columns of a vector from left to right and unique returns a column vector, so the "nonconformant arguments" are y (5×1) and unique(y) (3×1).
来源:https://stackoverflow.com/questions/8020403/1-of-k-coding-in-octave