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?
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
bsxfun(@eq, a', b)
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