Actually, think I figured out an answer. I can just use repmat to create a matrix of n copies of the vector, and use == with the vector to compare it that way.
Produce equality matrix based on elements in vector.
3 次查看(过去 30 天)
显示 更早的评论
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?
2 个评论
Guillaume
2020-3-27
"I can just use repmat"
You don't need repmat. Implicit expansion will take care of repeating the elements for you and will be faster. See my answer.
采纳的回答
Guillaume
2020-3-27
Trivially done.
%assuming A and B are both row vectors:
C = A.' == B;
If they're both column vectors, transpose B instead.
更多回答(3 个)
Bernd Wagner
2020-3-27
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
2020-3-27
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!