Wanderer
Wanderer

Reputation: 253

Matrix operations without loop MATLAB

I have matrix A(na*7) and matrix B(nb*7). (ex. A(16*7) and matrix B(110*7)) A and B both have 1's and 0's as context.

I want to perform xor operation between each row of A and each row of B and count the number of 1's in the result and store it to another matrix C of size na*nb.

I know how to do so with for loops but I am wondering if there is any elegant way to do so without for loops in order to save speed.

For example

If size of A is 3*2 and size of B is 4*2 i want to perform these operations:

sum(xor(A(1,:),B(1,:)))

sum(xor(A(2,:),B(1,:)))

sum(xor(A(3,:),B(1,:)))

l--------------l

sum(xor(A(1,:),B(2,:)))

sum(xor(A(2,:),B(2,:)))

sum(xor(A(3,:),B(2,:)))

l--------------l

sum(xor(A(1,:),B(3,:)))

sum(xor(A(2,:),B(3,:)))

sum(xor(A(3,:),B(3,:)))

l--------------l


sum(xor(A(1,:),B(4,:)))

sum(xor(A(2,:),B(4,:)))

sum(xor(A(3,:),B(4,:)))

Then I want each result to be stored in C. every set of 3 result is one row of C

Thanks a lot

Upvotes: 1

Views: 163

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112749

You can do that using pdist2 with the 'hamming' option:

C = pdist2(A,B,'hamming')*size(A,2);

Upvotes: 0

Rafael Monteiro
Rafael Monteiro

Reputation: 4549

You could do it with bsxfun and permute:

C = sum(bsxfun(@xor, permute(A, [1 3 2]), permute(B, [3 1 2])), 3)

Upvotes: 1

Related Questions