I have a vector y of length n. y(i) is an integer in 1..m. Is there a simpler way to convert y into an n x m logical matrix yy, where yy(i, j) = 1 if y(i) = j, but 0 otherwise? Here's how I've been doing it:
% If m is known (m = 3 here), you could write it out all at once
yy = [y == 1; y== 2; y == 3];
yy = reshape(yy, n, 3);
or
% if m is not known ahead of time
yy = [ y == 1 ];
for i = 2:m;
yy = [ yy; y == i ];
end
yy = reshape(yy, n, m);
as. logical() function in R Language is used to convert an object to a logical vector.
You can use logical vectors to extract a selection of rows or columns from a matrix, for example, if a is the original 3-by-3 matrix defined above, the statement: From: Essential Matlab for Engineers and Scientists (Fifth Edition), 2013.
L = logical( A ) converts A into an array of logical values. Any nonzero element of A is converted to logical 1 ( true ) and zeros are converted to logical 0 ( false ). Complex values and NaNs cannot be converted to logical values and result in a conversion error.
You can use bsxfun for this
yy = bsxfun(@eq,y(:),[1,2,3])
y
is transformed (if necessary) to a column-vector, while the other vector is a row vector. bsxfun
implicitly expands the m-by-1 and 1-by-n arrays so that the result becomes m-by-n.
If n*m is sufficiently large (and m is, by itself, sufficiently large), it is a good idea to create yy
as a sparse matrix. Your y
vector is really a special type of sparse matrix format, but we can translate it into the built-in sparse matrix format by doing the following.
yy = sparse(1:length(y), y, 1);
This will keep your storage to O(n). It is not going to be doing you a lot of favors if you are using yy
for a lot of indexing. If that is the case you are better off using your original sparse structure (i.e., y
).
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