英文:
setdiff among 2 vectors 1st vector vs each element of 2nd vector
问题
有没有一种向量化的方法,避免使用for循环,来得到一个矩阵M=[2 3 4;1 3 4;1 2 3],该矩阵表示了向量A与向量B的setdiff的结果?
英文:
I have 2 vectors let us say A=[1 2 3 4] and B=[1 2 4]. Using a for loop I can compute setdiff of A with each element of B. Giving the following vectors C1=[2 3 4], C2=[1 3 4], C3=[1 2 3].
Is there a way to achieve this in a vectorized form avoiding any for loop to get a Matrix M=[2 3 4;1 3 4;1 2 3]?
答案1
得分: 1
这的确可能在类似您的示例的情况下实现:
A = [1 2 3 4]
B = [1 2 4]
intrim = repmat(A.', 1, numel(B))
M = reshape(intrim(B ~= A.'), [], numel(B)).'
生成结果:
M =
2 3 4
1 3 4
1 2 3
如果您喜欢,甚至可以使用 subsref 来将其压缩成一行代码。
但进一步泛化(例如,如果扩展后的两个集合仍然包含多个元素)可能会更具挑战性。
英文:
It is indeed possible for cases similar to your example
A=[1 2 3 4]
B=[1 2 4]
intrim=repmat(A.',1,numel(B))
M=reshape(intrim(B~=A.'),[],numel(B)).'
produces
M =
2 3 4
1 3 4
1 2 3
It could even be squeezed into an one-liner with subsref, if that's your thing.
But further generalizing (e.g. if both set after expansion still contains multiple elements) might be challenging.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论