Union of 2 sets using MATLAB

The union A ∪ B of two sets A and B is defined as A ∪ B = {x : x ∈ A or x ∈ B};
If A = {1, 3, 5} and B = {1, 2, 3, 9}, then A ∪ B = {1, 2, 3, 5, 9}.
Thus essentially the union of sets A and B is the set with unique elements in set A or B, or both. This includes disregarding duplicate elements in a given set.

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

MATLAB CODE:

clc
x=input('Enter the first array');
y=input('Enter the second array');
z=[];
z=[z x];
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:


SAMPLE OUTPUT:

JAVA Code:

import java.util.Scanner;
class Oo
{
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();
}
for(int i=0;i<l;i++)
{
System.out.print(a[i]+" ");
}
int m=0;
int yr=0;
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+" ");
}
}
}
}

SAMPLE OUTPUT:





No comments