繁体   English   中英

如何从一个向量中删除一个向量的元素?

[英]How do I remove the elements of one vector from another?

我有一个双精度值A,即

[1,4,7,6]

我也有B,这是一个包含更多值的数组。 我有一个新的变量C,它实际上是所有这些数字的双精度值(它们全部集中在一个单元格中,而不是五个)。

[1,4,7,6]
[2,6,9,12]
[3,1,17,13]
[5,7,13,19]
[1,5,9,15]

如何从C中删除元素(不是实际值)? 我想以此结束。

 [2,6,9,12,3,1,17,13,5,7,13,19,1,5,9,15]

我怎么得到这个? 我使用了以下命令:

C(A) = [];

C = C(setdiff(1:length(C),A));

问题是,当我运行该命令时,得到的不是我想要的。

[4,7,2,12,3,1,17,13,5,7,13,19,1,5,9,15]

显然,这与我所拥有的不一样。 它影响了我的其余结果,我需要解决此特定问题。

提前致谢 :)

编辑:

所以我发现它以错误的顺序喷出了正确的数字。 我必须对其进行排序以使其正常工作。 这是一个问题,因为它会导致下一个命令不起作用,因为ismember命令的删除存在问题(我不知道为什么,我仍在处理它)。

双阵列盒

如果B是双setdiff数组,则可以将setdiff'rows''stable'选项一起使用,如下所示-

C = reshape(setdiff(B,A,'rows','stable').',1,[])

使用ismember ,您可以执行相同的操作,如下所示-

C = reshape(B(~ismember(B,A,'rows'),:).',1,[])

您也可以使用bsxfun建议的bsxfun方法-

C = reshape(B(~all(bsxfun(@eq, B, A),2),:).',1,[])

单元阵列盒

如果B是一个单元格数组,每个单元格中的元素数等于A的元素数,则可以先将其转换为双B = vertcat(B{:})数组B = vertcat(B{:}) ,然后使用上述任何一个工具。

或者,您可以使用基于cellfun的方法,避免转换为双cellfun数组,如下所示-

excl_rows = B(~cellfun(@(x1,x2) isequal(x1,x2), B, repmat({A},size(B,1),1)),:)
C = horzcat(excl_rows{:})

或另cellfun基于cellfun的避免repmat的方法-

exclB = B(~cellfun(@(x1) isequal(x1,A), B),:)
C = horzcat(exclB{:})

带说明的示例-

%// Inputs
A = [1,4,7,6]
B = {[1,4,7,6]
    [2,6,9,12]
    [3,1,17,13]
    [5,7,13,19]
    [1,5,9,15]}

%// Compare each cell of B with A for equality.
%// The output must be a binary array where one would be for cells that have 
%// elements same as A and zero otherwise.
ind = cellfun(@(x1) isequal(x1,A), B) 

%// Thus, ~ind would be a binary array where one would reperesent unequal 
%// cells that are to be selected in B for the final output.
exclB = B(~ind)

%// exclB is still a cell array with the cells that are different from A.
%// So, concatenate the elements from exclB into a vector as requested.
C = horzcat(exclB{:})

输出-

A =
     1     4     7     6
B = 
    [1x4 double]
    [1x4 double]
    [1x4 double]
    [1x4 double]
    [1x4 double]
ind =
     1
     0
     0
     0
     0
exclB = 
    [1x4 double]
    [1x4 double]
    [1x4 double]
    [1x4 double]
C =
     2     6     9    12     3     1    17    13     5     7    13    19     1     5     9    15

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM