Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert vector into logical matrix?

Tags:

matlab

octave

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);
like image 532
notrick Avatar asked Nov 08 '11 01:11

notrick


People also ask

How do you convert to logical in R?

as. logical() function in R Language is used to convert an object to a logical vector.

What is a logical vector in MATLAB?

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.

How do you write logical in MATLAB?

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.


2 Answers

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.

like image 194
Jonas Avatar answered Oct 12 '22 13:10

Jonas


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).

like image 20
David Alber Avatar answered Oct 12 '22 12:10

David Alber