如何检查一个数组中的任何变量是否在另一个数组中

时间:2013-12-08 19:13:01

标签: arrays matlab for-loop

我正在开发一个使用MatLab的程序,它计算数字的幂,将它们加在一起,然后查看第一组数字(数字到幂)中的任何一个是否等于任何增加的数字。我试图检查第一个数组中的每个值,但是,我得到这样的输出:

m =
       1
     128
    2187
   16384
   78125
  279936
  823543
 2097152
 4782969
10000000

表示每个m值,这只是数组的简单for循环的结果。所以当我去检查数组中是否m时,它在数组中检查是[1, 128,2187,16384,78125...],答案是否定的。如何评估每个条目,如下所示:

Array n is [1,128,2187,16384]
for m = n
m = 1
Is m in array? No
m = 128
Is m in array? No
m = 2187
Is m in array? Yes
m = 16384
Is m in array? No
end

我的代码如下:

C = [];
D = [];
E = [];
F = [];
numbers1 = [];
numbers2 = [];

numbers = 10;
powers = 10;

for i = 1:numbers 
    for j = 3:powers  
        C = [C;i^j]; 
    end  
    C = transpose(C);
    D = [D;C];  
    C = [];
end

[~,b] = unique(D(:,1)); % indices to unique values in first column of D
D(b,:);                  % values at these rows

for i = D
    for a = D
        E = [E;i+a];
    end
    E = transpose(E);
    F = [F;E];  
    E = [];
end

[~,b] = unique(F(:,1)); % indices to unique values in first column of F
F(b,:);                  % values at these rows

for m = D % this is the for loop mentioned above
        m
end

1 个答案:

答案 0 :(得分:2)

示例向量:

>> m = [1 3 5 9];
n = [5 2 1 4 8];
  1. 要检查向量m的每个元素是否在n中,请使用ismember

    >>ismember(m,n)
    ans =
         1     0     1     0
    
  2. 要获取值,而不是索引:在m上使用逻辑索引:

    >> m(ismember(m,n))
    ans =
         1     5
    

    或直接使用intersect

    >> intersect(m,n)
    ans = 
         1     5