Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two vectors of unequal lengths to get a logical array

I need to vectorize the following code:

a = [1 2 3 2 3 1];
b = [1 2 3];

for i = 1:length(a)
    for j = 1:length(b)
        r(i, j) = (a(i) == b(j));
    end
end

The output r should be a logical array:

 1     0     0
 0     1     0
 0     0     1
 0     1     0
 0     0     1
 1     0     0

The closest I can get is:

for j = 1:length(b)
    r(:, j) = (a == b(j));
end

Iterating through the shorter vector is obviously more efficient as it generates fewer for iterations. The correct solution should have no for-loops whatsoever.

Is this possible in MATLAB/Octave?

like image 607
Superbest Avatar asked Nov 11 '11 22:11

Superbest


2 Answers

Here's a simple solution using bsxfun.

bsxfun(@eq,b,a')

ans =

     1     0     0
     0     1     0
     0     0     1
     0     1     0
     0     0     1
     1     0     0
like image 66
abcd Avatar answered Sep 28 '22 23:09

abcd


bsxfun(@eq, a', b)

like image 22
vharavy Avatar answered Sep 28 '22 23:09

vharavy