2 views (last 30 days)

Given two equally sized vectors A and B, is there any way to make a matrix C of 1's and zero's such that the kth row of C contains 1's wherever elements of B equal the kth element of A?

I can do it by looping through elements of A, but I want to know if there's a vectorised way of doing this to speed it up?

Guillaume
on 27 Mar 2020

Trivially done.

%assuming A and B are both row vectors:

C = A.' == B;

If they're both column vectors, transpose B instead.

Bernd Wagner
on 27 Mar 2020

Does the Logical opperator C= A==B not do that work?

It compares values in Vector A and responds a logical value 1 if the Value is also on the same line in B. Hence your C vector will be a vector of 0 and 1 with 1 if A==B.

darova
on 27 Mar 2020

Try bsxfun

% make all combinations using bsxfun

C = bsxfun(@minus,b(:),a(:)'); % b - rows, a - columns

[i,j] = find(~C); % find 'zero'

C1 = C*0;

C1(i,:) = 1; % make entire row '1' if any element a==b

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
## 2 Comments

## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/513392-produce-equality-matrix-based-on-elements-in-vector#comment_816477

⋮## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/513392-produce-equality-matrix-based-on-elements-in-vector#comment_816477

## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/513392-produce-equality-matrix-based-on-elements-in-vector#comment_816479

⋮## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/513392-produce-equality-matrix-based-on-elements-in-vector#comment_816479

Sign in to comment.