Intersection of 2 sets using MATLAB

In mathematics, the intersection A ∩ B of two sets A and B is the set that contains all elements of A that also belong to B, but no other elements. 
Example:

First set:[7 1 5 2 3 6]

Second set:[3 8 6 20 7]

Output:[3     6     7]


Note that the elements of union and intersection can be printed in any order.

Prerequisite:



MATLAB CODE:

clc
x=input('Enter the first array');
y=input('Enter the second array');
z=[];
for i=1:length(y)
    m=y(i);
    s=0;
    for i=1:length(x)
        if(m==x(i))
            s=s+1;
        end
    end
    if(s~=0)
        z=[z m];
    end
end
disp(z);

        
Explanation:




Output:



JAVA CODE:

import java.util.Scanner;
class Oa
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the first array length:");
int l=obj.nextInt();
System.out.println("Enter the second array length:");
int p=obj.nextInt();
int a[]=new int[l];
int b[]=new int[p];
System.out.println("Enter "+l+" items");
for(int i=0;i<l;i++)
{
a[i]=obj.nextInt();
}
System.out.println("Enter "+p+" items");
for(int i=0;i<p;i++)
{
b[i]=obj.nextInt();
}
int m=0;
int yr=0;
System.out.println("Intersection of two arrays is:");
for(int i=0;i<p;i++)
{
m=b[i];
yr=0;
for(int k=0;k<l;k++)
{
if(m==a[k])
{
yr=yr+1;
}
}
if(yr!=0)
{
System.out.print(m+" ");
}
}
}
}

Output:



No comments